arraysccharacternull-character

Why is there a difference between the size of these two arrays with the same characters in C?


I created two arrays 'TEST' and 'arr' below,both contain characters "ABCDE".

#include <stdio.h>
#define TEST  "ABCDE" 
int main()
{
  char arr[5];
  int i;
  for(i=0;i<5;i++)
  {
       arr[i] = i + 65;
  }
  printf("%s\n",arr);
  printf("%zd %zd",sizeof arr,sizeof TEST);
  return 0;
}

And the output is

ABCDE
5 6

Why are their size different, given that these two arrays both carry 5 characters ? (I konw there is a null character at the end of each character string.)


Solution

  • After the macro expansion, the line

    printf("%zd %zd",sizeof arr,sizeof TEST);
    

    will be:

    printf("%zd %zd",sizeof arr,sizeof "ABCDE" );
    

    String literals will always have a terminating null character added to them. Therefore, the type of the string literal is char[6]. The expression sizeof "ABCDE" will therefore evaluate to 6.

    However, the type of arr is char[5]. Space for a null-terminating character will not be automatically added. Therefore, the expression sizeof arr will evaluate to 5.

    Also, it is worth noting that the following line is causing undefined behavior:

    printf("%s\n",arr);
    

    The %s printf format specifier requires a null-terminated string. However, arr is not null-terminated.

    If you want to print the array, you must therefore limit the number of characters printed to 5, like this:

    printf( "%.5s\n", arr );
    

    Or, if you don't want to hard-code the length into the format string, you can also do this:

    printf( "%.*s\n", (int)sizeof arr, arr );