Sizes of arrays declared with pointers

后端 未结 5 1717
走了就别回头了
走了就别回头了 2021-01-23 14:24
char c[] = \"Hello\";
char *p = \"Hello\";

printf(\"%i\", sizeof(c)); \\\\Prints 6
printf(\"%i\", sizeof(p)); \\\\Prints 4

My question is:

Why

5条回答
  •  长情又很酷
    2021-01-23 14:52

    It sounds like you're confused between pointers and arrays. Pointers and arrays (in this case char * and char []) are not the same thing.

    • An array char a[SIZE] says that the value at the location of a is an array of length SIZE
    • A pointer char *a; says that the value at the location of a is a pointer to a char. This can be combined with pointer arithmetic to behave like an array (eg, a[10] is 10 entries past wherever a points)

    In memory, it looks like this (example taken from the FAQ):

     char a[] = "hello";  // array
    
       +---+---+---+---+---+---+
    a: | h | e | l | l | o |\0 |
       +---+---+---+---+---+---+
    
     char *p = "world"; // pointer
    
       +-----+     +---+---+---+---+---+---+
    p: |  *======> | w | o | r | l | d |\0 |
       +-----+     +---+---+---+---+---+---+
    

    It's easy to be confused about the difference between pointers and arrays, because in many cases, an array reference "decays" to a pointer to it's first element. This means that in many cases (such as when passed to a function call) arrays become pointers. If you'd like to know more, this section of the C FAQ describes the differences in detail.

    One major practical difference is that the compiler knows how long an array is. Using the examples above:

    char a[] = "hello";  
    char *p =  "world";  
    
    sizeof(a); // 6 - one byte for each character in the string,
               // one for the '\0' terminator
    sizeof(p); // whatever the size of the pointer is
               // probably 4 or 8 on most machines (depending on whether it's a 
               // 32 or 64 bit machine)
    

提交回复
热议问题