c - Why local array value isn't destroyed in function? -
void func(){ int i; char str[100]; strcat(str, "aa"); printf("%s\n", str); } int main(){ func(); func(); func(); return 0; }
this code prints:
?@aa ?@aaaa ?@aaaaaa
i don't understand why trash value(?@)
created, , why "aa"
continuously appended. theoretically local values should destroyed upon function termination. code doesn't.
to use strcat()
need have valid string, uninitialized array of char
not valid string.
to make valid "empty" string, need this
char str[100] = {0};
this creates empty string because contains null terminator.
be careful when using strcat()
. if intend 2 concatenate valid c strings it's ok, if more 2 it's not right function because way wroks.
also, if want code work, declare array in main()
instead , pass function, this
void func(char *str) { strcat(str, "aa"); printf("%s\n", str); } int main() { char str[100] = {0}; func(str); func(str); func(str); return 0; }
Comments
Post a Comment