I tried some code to check the behavior of array and pointers. Its as follows.
#include <stdio.h>
main(){
int s[]={1,2};
int *b=s;
printf("%d, %d, %d\n", s, &s, *s);
printf("%d, %d, %d\n", b ,&b, *b);
}
Initially I thought of pointers and array to be same BUT…
To my surprise the value of ‘s’ and ‘&s’ are SAME unlike ‘b’. Does that mean an Array variable “points to itself?”
I am also now confused with what actually is a variable “name”? How its binding takes place with a location in memory? I am just unable to visualize things that go on there!
And where in memory (RAM) is all the information stored at run time?
Except when it is the operand of the
sizeofor unary&operators, or is a string literal being used to initialize another array in a declaration, an expression of type “N-element array ofT” will be replaced with an expression of type “pointer toT“, and the value of the expression will be the address of the first element in the array.Assume the following code:
In the call to the function
foo, the expressionarris converted from type “10-element array ofint” to “pointer toint“, and the address of the first element ofarris what actually gets passed tofoo.We would define
fooas eitheror
In the context of a function parameter declaration,
T a[]andT a[N]are identical toT *a; the parameter is a pointer type, not an array type. Note that this is only true for function parameter declarations.As mentioned above, one exception to this rule is when the array expression is the operand of the unary
&operator. If we change the call tofooto readthen the type of the expression
&arris “pointer to 10-element array ofint“, orint (*)[10], and the value of the expression is the address ofa. For this, the definition offoowould beIn C, the address of the array and the address of the first element of the array are the same – thus both of the expressions
arrand&arrhave the same value, but their types are different. This matters for operations involving pointer arithmetic. For example, assume our code had been writtenOn entry,
apoints toarr[0]. The expressiona++would advance the pointer to point to the next integer in the array (arr[1]).Now assume the code had been written as
On entry,
astill points toarr[0](remember, the address of the array is the same as the address of the first element of the array), but this time the expressiona++will advance the pointer to point to the next 10-element array of integers; instead of advancing the pointersizeof (int)bytes, we advance itsizeof (int[10])bytes.So this is why in your
printfstatement you see the same values for bothsand&s. You should use the%pconversion specifier to print pointer values, and it expects the corresponding argument to be typevoid *, so change thoseprintfstatements to