tags:

views:

364

answers:

6

I stumbled upon this odd result when I was messing around with C arrays:

char s[100] = "hello";
if(s == &s[0]) printf("true. ");
if(s == &s) printf("true.");
// output: true. true.

I know that s holds the memory location of the first element, but is there a way to find the address of s (the address of the pointer that points to the first element)? Why does &s equal s? Not that this is useful, but I'd like to know what's going on under the hood.

I'm not sure if different compilers implement it differently, but I am using gcc.

+9  A: 

That's because s is not a pointer, but an array. Arrays are automatically casted to pointers when necessary (as in strcpy etc.), but there is no such thing as "the address of the pointer that points to the first element". s is just 100 bytes on the stack; the compiler passes the address of those 100 bytes to function calls whenever a pointer is needed.

ammoQ
+11  A: 

If I told you to put your finger on the place in memory where the character array s is located, and then where the first character in the array is located, wouldn't they be the same?

le dorfier
My finger is pointing to the same place. Thanks!
Elben Shira
Lovely analogy, I'll have to remember that one.
Mark Ransom
+4  A: 

The array s does not hold a memory address (i.e. pointer), it actually holds all the characters.

C will freely convert an array to a pointer to the array.

The pointer to an array is the same as the pointer to its first element.

Mark Ransom
+1  A: 

On the other hand, you can also do things like this:

char (*t)[100] = s;
if(t == &t[0]) printf("true 3. ");
if(t == &t) printf("true 4.");

In that case, t is indeed a pointer to an array of characters that has its own storage and address. Case 3 is true and case 4 is false.

Greg Hewgill
FYI gcc warns on your initialization for t, prefering `char (*t)[100] =
rampion
A: 
Value of &s, s and &s[0] are same, but their types are not same.
type of &s is char (*)[100], but type of s and &s[0] is char*.
&s is a pointer to the entire array but s and &s[0] points to
the first element of the array.
sizeof(&s) and sizeof(s) is 100, but sizeof(&s[0]) is 4.
Similarly if s = 1000, then &s+1 returns 1100 but s+1 and &s[0]+1 returns 1001.
Shino C G
+3  A: 

&s[0] means the address of the first element of array s. The type of &s[0] is char *.

&s means the address of array s. The type of &s is char (*)[100].

&s[0] + 1 is the address of next 1 byte. But &s + 1 is the address of next 1*100=100 bytes.