-1

:)

this is my code:

int main(void)
{
    char num[11] = { "Mississippi" };

    printf("%p\n", &num); // prints 0x7fffe44a5eb0
    printf("%p\n", num);  // prints 0x7fffe44a5eb0
    printf("%c\n", *num); // prints M

    return EXIT_SUCCESS;
}

why do I get the same address for:

printf("%p\n", &num);

and for:

printf("%p\n", num);

?

shouldn't &num print the address of the pointer itself and num print the address of the 'cell' where M is stored?

any input is greatly appreciated! cheers

1 Answers1

3

No, an array is not a pointer. But it can decay to a pointer to its first element. Which is why num is the same as &num[0]. The type of this pointer is char *.

The expression &num is a totally different one though, as it's a pointer to the array itself. The type of this is char (*)[11]. It just so happens that both num (and therefore &num[0]) and &num are pointing to the same location, but since they are different types they are semantically different.

Somewhat "graphically" you could see your array like this:

+---+---+---+---+---+---+---+---+---+---+---+
| M | i | s | s | i | s | s | i | p | p | i |
+---+---+---+---+---+---+---+---+---+---+---+
^   ^   ^                                   ^
|   |   |                                   |
|   |   &num[2] ...                         &num[11]
|   |                                       |
|   &num[1]                                 (&num)[1]
|
&num[0]
|
&num

And to repeat, plain num will decay (i.e. be translated by the compiler) to &num[0]. And both &num and &num[0] points to the same location, but are of different types.


On another note, remember that char strings in C are really called null-terminated byte strings. This null-terminator is what makes a string a string, and all string-handling functions use this terminator to know where the end of the string is.

You array does not have the space for this terminator.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • thank you for responding! I still don't understand, though, why the address of the pointer itself and the value of the pointer could ever be the same. it's like the pointer is pointing on itself...which should be useless? – Bobstanley May 31 '18 at 10:10
  • @Bobstanley Updated with an "image" to hopefully make it clearer. – Some programmer dude May 31 '18 at 10:15