While learning C language, one of the things that I noticed being mentioned in tutorials were using "Arrays and Pointers and interchanegbly". In this post, I'll try to explain what I learnt :-
To start with Arrays and Pointers are NOT same. Arrays are arrays and pointers are pointers. Depending upon the context (mostly), array names are implicitily converted to pointers. When an array is
If we have an expression like
// Declare an array of integer type which can hold 10 values and an integer pointer
int a[10];
int *ap;
When an array is used an an value, its name represents the address of the first element. When an array is not used as an value, its name represents the whole array.
// Here array "a" holds the address of the first element.
// a[2] is actually referenced by address of first element + offset (index of array) (i.e. pointer arithemetic is used)
// When an array is de-refernced [] then x[y] can be considered as pointer arithemetic of *(x+y), where x is the starting addres
a[2] = 10;
We can also write something like
// Here a is considered as a pointer (implicit conversion) i.e. this statement will copy the address of first element of array a to ap
ap = a;
This is same as
ap = &a[0];
In cases like using sizeof and & operands, then the array name is not converted to pointers and are used as such.
size_t bytes = sizeof(a);
void *ap = &a;
One more point here to note here is difference between "&a" and "a"
int array[10];
array // Gives the array name i.e. the address of first element (pointer to an integer i.e. int *)
&array // Gives the address of array name (pointer to an array of 10 integers i.e. (int *)[10] )
If you try to print the address of first element of array, then both array and &array will point to same memory location. But the difference comes up when you do pointer arithemetic i.e. increment the value by 1.
Now in this case, when we incremenet the address as array+1, then it will point to array element with index 1. It will decay the array to the address of first element and then add sizeof(int) to get the value of second element of array.
However when we use (&array + 1), since the &array is a pointer to array of 10 elements, incrementing 1 will result in size addition of 10*sizeof(int), so it won't reference the second element of array.
Comments
Post a Comment