How come the first element of an array is equal to the array ?. Lets say you have an integer array like int arr[5];
then according to your question headline
- first element of an array will be
arr[0]
which is value of arr[0]
and
- array means
arr
and arr
names represents base address of the array. So arr
and arr[0]
are not same. arr
is base address & arr[0]
is value.
For your particular case, integer array a
looks like below & all elements of array are stored in consecutive memory location. Assume array base address is 0x100
(some memory location)
a[0] a[1] a[2] a[3] ........................................ a[9]
------------------------------------------------------------------------
| 2 | 4 | 6 | 8 | 10 | 12 | 14 | 16 | 18 | 20 | 22 |
------------------------------------------------------------------------
0x100 0x104 0x108 .. ..
a
LSB MSB
So here a
means 0x100
, by assuming base address of a
is 0x100
. Now when you do
p = &a[0]; /* here you are setting p to point to one of the places in the array a and that is a[0] */
here p
is pointing to first
element of a
i.e 0x100
as below
a[0] a[1] a[2] a[3] ........................................ a[9]
------------------------------------------------------------------------
| 2 | 4 | 6 | 8 | 10 | 12 | 14 | 16 | 18 | 20 | 22 |
------------------------------------------------------------------------
0x100 0x104 0x108 0x112 0x116.. ..
a
|
p
Now when you print a[4]
it prints 10
which is quite simple as expected & it expands like below
a[4] = *(a + 4) /* here you can say that array name a is converted to a pointer to its first element */
= *(0x100 + 4*4 ) /* multiplied by 4 ? bcz a is int array & each element size is 4 byte */
= *(0x116) /* value at 0x116 memory location */
= 10
And when you print p[4]
it expands like below
p[4] = *(p + 4)
= *(0x100 + 4*4) /*multiplied by 4 because int pointer increments by 4 bytes*/
= *(0x116) ? /* it prints value at 0x116 location which 10 */
= 10
Also while assigning values to array elements in the for loop
, you are trying to access a[10]
which is out of boundary & causes undefined behavior. In the below code block condition part should be i<10
instead of i<=10
as you declared a[10]
and array index starts from zero
.
for(i = 0;i <=10;i++) { /* make it i<10 */
a[i] = (i + 1) * 2;
}
Finally void main() { /* code */ }
is bad practice and its not according to C standards specification. Use int main(void) { }
instead as specified in C standard n1256
draft.
5.1.2.2.1 Program startup
1 The function called at program startup is named main. The
implementation declares no prototype for this function. It shall be
defined with a return type of int and with no parameters:
int main(void) { /* ... */ }
or with two parameters (referred to here as argc and argv, though any
names may be used, as they are local to the function in which they are
declared):
int main(int argc, char *argv[]) { /* ... */ }
or equivalent;9) or in some other implementation-defined manner.