-3

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.)

Sym Laq
  • 3
  • 1
  • 7
    "konw there is a null character at the end of each character string.": I am not sure where you think a null character would be in `arr`. Could you explain your reasoning that the two `sizeof` expressions should have the same result? – user17732522 Dec 29 '21 at 01:50
  • I supposed the size of 'arr' should be 6, but it seems there is no place for 'arr' to store the null character? – Sym Laq Dec 29 '21 at 02:17
  • If you tell the compiler that `arr` has five slots, that's what it has. If you then put non-zero characters in all five slits, then you cannot use the array as a string. That's not a problem for the compiler. Arrays don't have to be usable as strings. – rici Dec 29 '21 at 02:19

1 Answers1

1

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 );
Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39