Reputation: 35
#include <stdio.h>
int main()
{
int a[5];
printf("%p\n%p\n",a+1,&a[1]);
return(0);
}
When the above code is built and run. The output is:
0029ff00
0029ff00
Then when i change the 5th line from a + 1
to &a + 1
#include <stdio.h>
int main()
{
int a[5];
printf("%p\n%p\n",&a+1,&a[1]);
return(0);
}
The output is:
0029ff10
0029ff00
what is being referred to when i include the ampersand (&
) and does it have to do with the format specifier %p
?
Upvotes: 1
Views: 91
Reputation: 106122
&a[1]
is equivalent to &*(a + 1) = (a + 1)
and that's why first snippet prints the same address value.
&a
is the address of array a
. It is of type int (*)[5]
. Adding 1
to &a
will enhance it to one past the array, i.e. it will add sizeof(a)
bytes to &a
.
Suggested reading: What exactly is the array name in c?.
Upvotes: 0
Reputation: 11
Sign "&" is address of element after & sign so in printf,it will print out memory address of your element.
and does it have to do with the format specifier %p?
%p is accessing to pointer(address that pointer is reffering to) and that's why you get values like 'x0000'...
Try using %d or %i for integer values in your tasks.
Upvotes: 0
Reputation: 16607
printf("%p\n%p\n",&a+1,&a[1]);
In this line both address are different because &a[1]
gives address of a[1]
and &a+1
gives address that is one past the last element of array .
&a
give address of array and adding 1
to it adds size of array to base address of array a
.
So basically , &a+1
= Base address of array a
+ size of array a
(that address is printed)
Upvotes: 4
Reputation: 2566
The '&' means "address of", and the %p format means print the value as a pointer (address), which prints it in hex. When doing "pointer arithmetic", when you add 1 to a pointer, the pointer is incremented (1 * sizeof(type)) where "type" is the type of data being pointed to.
Remember, in C, an array variable is a pointer. &a is not the address of the array, but the address where the address of the array is stored. So, when you add 1 to &a, &a contains a, which is a pointer, so (&a + 1) is (&a + size(a)), and since a is an array, it's the size of the array. In this case, an array of 4 ints is 16 bytes.
Upvotes: -1