1
#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?

2
  • 1
    Read section 6 of the comp.lang.c FAQ. Commented Nov 11, 2015 at 18:53
  • 1
    a and &a give the same address, but different types. So a + 1 moves by the size of an int, but &a + 1 moves by the size of a 5 element array of int. Commented Nov 11, 2015 at 18:59

4 Answers 4

4
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)

Sign up to request clarification or add additional context in comments.

2 Comments

base address of array?
@Atom Address of first element of array &a[0].
0

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.

1 Comment

The values he gets are fine, and wrong speciffiers should not be used .
0

&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?.

Comments

-1

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.

1 Comment

"Remember, in C, an array variable is a pointer" – he better not remember such bulls**t. "&a is not the address of the array" – it absolutely is.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.