Consider the following program.
#include <stdio.h>
int main()
{
int a[10]={0};
printf("%p %p\n", a, &a);
printf("%d %d\n", *a, *(&a));
return 0;
}
a and &a are same. But *a and *(&a) are not. I am out of answers. Please help.
Consider the following program.
#include <stdio.h>
int main()
{
int a[10]={0};
printf("%p %p\n", a, &a);
printf("%d %d\n", *a, *(&a));
return 0;
}
a and &a are same. But *a and *(&a) are not. I am out of answers. Please help.
a[i]
is the same as *(a + i)
. So the first element is at the same address as the array itself.
You'll find a more detailed explanation in another question here on SO: How come an array's address is equal to its value in C?
The address of an array is one of those things you learn early on in C. The address of the buffer is the address of its first element. In the case of
printf("%d %d\n", *a, *(&a));
*a
takes the value of a.
*(&a)
first take's a's address, and then deferences from that.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char szBuffer[100];
char *pBufferPtr = NULL;
int main(int argc, char *argv[])
{
pBufferPtr = szBuffer;
printf("%s %i\n %s %i\n %s %i\n",
"szBuffer's address: ", (int ) szBuffer,
"&szBuffer[0]'s address: ", (int ) &szBuffer[0],
"pBufferPtr's address: ", (int ) pBufferPtr);
printf("\n%s\n", "Program ended.");
return 0;
}
As I learned many years ago, sometimes the best thing to do with pointers is write what used to be called "stub" code, and then examine in the debugger or use "print" (printf) statements. What gets trickier is when you want to modify what a pointer points to, instead of its contents.
There is no "array base pointer", i.e. there no pointer variable that points to the array. The name of the array refers to the array itself. Therefore you can not take an address of a
, instead, &a
is handled as a special case.
When you use the name of an array in an expression, it decays into a pointer that points to the first element of the array. However, &
and sizeof
operators are exceptions.
ANSI C specifies that &a
means the address of the array itself, and its type is "pointer to array", not "pointer to array element".
In pre-ANSI compilers, &a would cause a warning.
a
and &a
have the same value, but they are different types: int *
and int **
. You should have got a warning when you compiled you code.
Your second line will work if you add an extra *
like this:
printf("%d %d\n", *a, **(&a));
This does make sense: if *a
dereferences a
and gives the first element of the array, and &a
means take the address of a
, then *(&a)
takes the address of a
, dereferences that, and arrives back at a
once more.