Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - (ptr = = &ptr) What is *ptr?

Tags:

arrays

c

pointers

This might be a stupid question, but I have a little problem with understanding of C Pointers. Even more when it comes to arrays. For example:

char ptr[100];
ptr[0]=10;

fprintf(stderr, "&ptr: %p \n ptr: %p \n*ptr: %d\n", &ptr, ptr, *ptr);

if ( &ptr == ptr ) {
  fprintf(stderr, "Why?\n");
}

How is this even possible? 'ptr' is at the adress &ptr. And the content of ptr is the same as &ptr. Then why is *ptr = 10 ???

like image 398
jfreax Avatar asked May 29 '26 08:05

jfreax


2 Answers

The address of the first element of the array is the same as the address of the array itself.

Except when it is the operand of the sizeof or address-of & operators, or is a string literal being used to initialize another array in a declaration, an expression of type "N-element array of T" will be implicitly converted ("decay") to type "pointer to T" and the value will be the address of the first element in the array.

If the expression a is of type "N-element array of T", then the expression &a is type "pointer to N-element array of T", or T (*)[N].

Given the declaration

T a[N];

then the following are all true:

Expression         Type        Decays to
----------         ----        ---------
         a         T [N]       T *
        &a         T (*)[N]    n/a
        *a         T           n/a

The expressions a and &a both evaluate to the same value (the location of the first element in the array), but have different types (pointer to T and pointer to array of T, respectively).

like image 199
John Bode Avatar answered May 31 '26 22:05

John Bode


ptr (which, as sbi says, is really an array) decays to &(ptr[0]) (char * to first element)

This is the same address as &ptr (a char (*) []), even though they are different types.

like image 45
Matthew Flaschen Avatar answered May 31 '26 23:05

Matthew Flaschen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!