1

I just made a test program after reading the book and the result turned out confusing:

    #include <stdio.h>
    int main(void)
    {
        char text[] = "hello!";

        printf("sizeof(text):%d  sizeof(text+2):%d  sizeof(text[0]):%d \n",(int)sizeof(text), sizeof(text+2), sizeof(text[0]));
        printf("text:%p sizeof(text):%d      &text:%p sizeof(&text):%d \n",text, sizeof(text), &text, sizeof(&text));
        printf("text+1:%p  &text+1:%p  \n", text+1, &text+1);

        return 0;
    }

The result:

sizeof(text):7  sizeof(text+2):4  sizeof(text[0]):1 
text:0xbfc8769d sizeof(text):7      &text:0xbfc8769d sizeof(&text):4 
text+1:0xbfc8769e  &text+1:0xbfc876a4 

What makes me feel confused are:

  1. why the value of 'sizeof(text)' is 7 whereas 'sizeof(text+2)' is 4
  2. what's the difference between 'text' and '&text'?
snowfox
  • 1,978
  • 1
  • 21
  • 21
  • The array-to-pointer decay happens "when it's necessary". For example, it's necessary in `text + 2`, since the `+` expression wouldn't otherwise make sense. – Kerrek SB Jun 05 '14 at 09:11

2 Answers2

1
text+2

is a pointer to the 3rd element in the array, so sizeof results in the size of the pointer

text is the array while &text is a pointer to the array text[1] is the second element in the array, but (&text)[1] points to the first element after the array (in that case equal to &text[7])

mch
  • 9,424
  • 2
  • 28
  • 42
1

Important: arrays are not pointer

they degrade to pointer if using them in contexts that expect a pointer.

  • sizeof(text) gets the array at a whole so it outputs 7;
  • sizeof(text+2) pointer arithmetic let the array degrade to a pointer
  • sizeof(text[0])size of an element of course
  • sizeof(&text) size of the pointer to the array. obviously a pointer too

using the address operates on an array explicitly retrieves a pointer to an array of that specific type (in your case char[7]. that pointer has the same address but a different type than a to-pointer-degraded array.

so the difference between text+1 and &text+1 should also be obvious. the first one increments the char pointer by one element --> points one element behind the first one. the second points to the second 7-element-char-array behind the first one.

vlad_tepesch
  • 6,681
  • 1
  • 38
  • 80