简体   繁体   中英

C programming Pointers and Arrays?

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

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)

&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, ie it will add sizeof(a) bytes to &a .

Suggested reading: What exactly is the array name in c? .

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM