array initialization

Status
Not open for further replies.

estranged12

Broken In
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}?
 

vandit

In the zone
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....
 

redhat

Mad and Furious
You can initialize arrays with just any element you want...

I think, you mean, array index
 

QwertyManiac

Commander in Chief
Um even though vandit has explained it, for the rest of you, his question was:

When we can declare-and-initialize an array as:

Code:
int x[3]={0,1,2};

Why can't one do it as:

Code:
int x[3];
x={0,1,2};
 

INS-ANI

In the zone
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

Pee into the Wind...
You say
Code:
int a[5];
a[3]=35;
Compiler treats it as
Code:
*(a+3)=35;
So, if you declare it like
Code:
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

In the zone
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.
 
Status
Not open for further replies.
Top Bottom