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.)
After the macro expansion, the line
will be:
String literals will always have a terminating null character added to them. Therefore, the type of the string literal is
char[6]. The expressionsizeof "ABCDE"will therefore evaluate to6.However, the type of
arrischar[5]. Space for a null-terminating character will not be automatically added. Therefore, the expressionsizeof arrwill evaluate to5.Also, it is worth noting that the following line is causing undefined behavior:
The
%sprintfformat specifier requires a null-terminated string. However,arris not null-terminated.If you want to print the array, you must therefore limit the number of characters printed to
5, like this:Or, if you don't want to hard-code the length into the format string, you can also do this: