Search code examples
ccharsizeof

sizeof char[]="some" is strange


char  string0[]=  "0123456789";  // sizeof(string0)=11
char  string1[11]="0123456789A"; // sizeof(string1)=11

The string1 case is clear, allocated 11 Bytes for chars plus one for '\0' and sizeof() do not count terminator.

The string0 case is not clear to me, allocated 10 Bytes for chars plus one for '\0', so sizeof() should report 10

Why sizeof() say the same size in both cases?


Solution

  • sizeof() do not count terminator"

    sizeof reports the size of the allocated memory. There is no counting involved. You might be mistaking sizeof for strlen, which indeed does not count the string terminator.

    The first one is auto-allocated, and is size 11 because you have 10 characters and NUL. The second is manually allocated to size 11, which is filled with 11 characters, with no NUL since there is no space for it; if you try to print it (or indeed apply strlen on it), you will get gibberish at best.

    See Why does gcc allow char array initialization with string literal larger than array?