问题
Probably I'm just too dump for googling, but I always thought char arrays get only null terminated by an literal initialization (char x[]="asdf";
) and got a bit surprised when I saw that this seems not to be the case.
int main()
{
char x[2];
printf("%d", x[2]);
return 0;
}
Output: 0
Shouldn't an array declared as size=2*char actually get the size of 2 chars? Or am I doing something wrong here? I mean it isn't uncommon to use a char array as a simple char array and not as a string, or is it?
回答1:
You are accessing an uninitialized array outside its bounds. That's double undefined behavior, anything could happen, even getting 0
as output.
In answer to your real question: Only string literals get null-terminated, and that means that char x[]="asdf"
is an array of 5
elements.
回答2:
char
arrays are not automatically NULL terminated, only string literals, e.g. char *myArr = "string literal";
, and some string char pointers returned from stdlib string methods.
C does no bounds checking. So an array declared as size 2*char
gives you 2 memory slots that you can use, but you have the freedom to walk all over the memory on either side of that, reading and writing and thereby invoking undefined behavior. You may see 0
bytes there. You may write to array[-1]
and crash your program. It is your responsibility to keep track of the size of your array and avoid touching memory that you didn't allocate.
It is common to use a char array as a simple char array, i.e. other than a C string, for instance, to hold any arbitrary buffer of raw bytes.
回答3:
If t
is an array of size 2
, then the last case is t[2 - 1] = t[1]
and not 2. t[2]
is out of bounds.
来源:https://stackoverflow.com/questions/11229477/are-all-char-arrays-automatically-null-terminated