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?
You can't initialise a char array with NULL , arrays can never be NULL .
C strings are null-terminated. That is, they are terminated by the null character, NUL . They are not terminated by the null pointer NULL , which is a completely different kind of value with a completely different purpose. NUL is guaranteed to have the integer value zero.
char * strchr ( const char * string, int c ); Find character in string. Returns the first occurrence of c in string. The null-terminating character is included as part of the string and can also be searched.
Yes - although your question sounds like you suspect otherwise... Yes, all string in C are represented by string 0 terminated. @AditiRawat '\0' is just a char with value 0, it can be checked against 0.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With