Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between a pointer and its address

Tags:

arrays

c

pointers

I am just trying to unveil the secrets of C and pointers (once again), and I had a question regarding pointers and decaying. Here is some code:

#include <stdio.h>

int main() {
    int array[] = { 1, 2, 3 };
    int (*p_array)[] = &array;

    printf("%p == %p == %p\n", array, &array, &array[0]);
    printf("%p == %p\n", p_array, &p_array);

    return 0;
}

When I run that, I get this output:

0x7fff5b0e29bc == 0x7fff5b0e29bc == 0x7fff5b0e29bc

0x7fff5b0e29bc == 0x7fff5b0e29b0

I understand that array, &array, &array[0] are all the same, because they decay to a pointer which point to the exact same location.

But how does that apply to actual pointers, here *p_array, which is a pointer to an array of int, right? p_arrayshould point to the location where the first int of the array is stored. But why is p_array's location unequal to &p_array?

Maybe it is not the best example, but I would appreciate if someone would enlighten me...

Edit: p_array refers to the address of the first element of the array, whereas &p_array refers to the address of the p_array pointer itself.

All the best, David

like image 221
DeBe Avatar asked Dec 07 '25 10:12

DeBe


2 Answers

I understand that array, &array, &array[0] are all the same, because they decay to a pointer which point to the exact same location.

No. You didn't understand. array is of array type and in most cases will convert to pointer to its first element. Therefore, array and &array[0] are same as an expression, except when operand of sizeof operator. &array is the address of array array and is of type int (*)[3]. Read here in details: What exactly is the array name in c?.

p_array is pointer to array array and store its address while &p_array is the address of p_array.

like image 186
haccks Avatar answered Dec 10 '25 03:12

haccks


But why is p_array's location unequal to &p_array?

&p_array is the address of the pointer itself (0x7fff5b0e29b0), whereas p_array is a pointer to array and its value is the address of array1, (0x7fff5b0e29bc).


1. The address of the first element.

like image 29
Ziezi Avatar answered Dec 10 '25 02:12

Ziezi