View Full Version : array initialization
estranged12
19-03-2008, 01:23 AM
when you initialize an array, why can you only declare its elements like {1,2,3} when you initialize it and not just like x = {5,6,7}?
aircombat
19-03-2008, 01:39 PM
Do u mean the Array Values or the Array Index ?
vandit
19-03-2008, 02:08 PM
Because after declaration the name(i.e x ) of the array points to the 1st element of the array..Hence when u write x={1,2,3} after declaration..The compiler tries 2 give the 1st element i.e. X[0] those vals. Which is not possible...Hence....
Pathik
19-03-2008, 03:02 PM
You can initialise it with whatever values you want.
redhat
19-03-2008, 03:35 PM
You can initialize arrays with just any element you want...
I think, you mean, array index
QwertyManiac
19-03-2008, 04:38 PM
Um even though vandit has explained it, for the rest of you, his question was:
When we can declare-and-initialize an array as:
int x[3]={0,1,2};
Why can't one do it as:
int x[3];
x={0,1,2};
INS-ANI
22-03-2008, 02:25 PM
let us undertand some basic things about array.
the given array is a[n].
so when we write a[n], we are telling the machine that it is an array with n elements.
the "n" is just an number,integer.
and the variable "a" is actually a pointer to the base address of the array, that is a[0].
so int x[3];
x={1,2,3} is wrong, as it means we are trying to give some value to the variable x, though this is not a correct way either.
so the only way to add values to array while initialisation is
x[]={ ....}
or x[3]={..}
shady_inc
24-03-2008, 11:58 AM
You say
int a[5];
a[3]=35;
Compiler treats it as
*(a+3)=35;
So, if you declare it like
int x[3];
x={0,1,2};
compiler will treat second line as :
*(x+0)={0,1,2};
Which is obviously wrong.
P.S.: You can declare int a[3]=35; as int 3[a]=35.Both mean the same as *(a+3)==*(3+a).! ;)
anand1
24-03-2008, 12:34 PM
It will result into a Syntax error simple. If you were the developer than you should have added this feature in it. Any Programming language has a specific Syntax which we should follow. And this if not followed will result into a Syntax error.
QwertyManiac
24-03-2008, 02:01 PM
anand1 - Yes, but behind every syntax point lies a great tale, which is what he asks. ;)
vBulletin® v3.7.0, Copyright ©2000-2008, Jelsoft Enterprises Ltd.