What occurs when assigning a string to char in C -
i appreciate understanding occur in next code? (writing "a" instead of 'a' , etc...). mean stored in memory , why isnt program crashes.
char str[10] ; str[0] = "a"; str[1] = "b"; str[2] = "\0";
thanks.
'a' single character (type char
) having ascii value 97. "a" c style string, char
array having 2 elements, 'a' , '\0'.
if compile code above 3 warnings 3 assignments. on gcc these warnings this:
main.c:6:12: warning: assignment makes integer pointer without cast [enabled default]
lets take first assignment in code:
str[0] = "a";
the right hand side operand, "a", char *
. left hand side operand char
, integer type. warning hints towards, takes value of pointer, converts integer, , truncates size of char
, stores truncated value in str[0]
. after assignment str[0]
not contain value 'a' (ascii 97) might expect, value obtained described above.
so far good, no reason program crash, note str
not contain meaningful string.
now if try useful string, print example:
printf("%s", str);
you find reason might crash program (or cause whole lot of other problems, memory corruption). problem last assignment, str[2] = "\0"
, doesn't terminate string might expect. end c-style string that's not null-terminated. sure , short path disaster.
to test behavior, try display actual values stored in str
after assignments:
printf("%d - %d - %d", str[0], str[1], str[2]);
you find different values ones might expect (97, 98, 0).
Comments
Post a Comment