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 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

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -