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?

Atom
  • 25
  • 1
  • 10
  • 1
    Read section 6 of the [comp.lang.c FAQ](http://www.c-faq.com/). – Keith Thompson Nov 11 '15 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`. – Dmitri Nov 11 '15 at 18:59

4 Answers4

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)

ameyCU
  • 16,489
  • 2
  • 26
  • 41
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?.

Community
  • 1
  • 1
haccks
  • 104,019
  • 25
  • 176
  • 264
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.

mmusic
  • 11
  • 1
-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.

DBug
  • 2,502
  • 1
  • 12
  • 25