This is my problem. The answer is 0-AAAA. #include <stdio.h> #include <string.h> int main(int argc,char*argv[]){ int i=1; char buf[4]; strcpy(buf,"AAAA"); printf("%d-%s\n",i,buf); return 0; }
I increased the size of buffer buf[5] and the answer is 1-AAAA. Is this the best solution? Could you explain me why I have this answer, because I'm new in C/C++?
"I increased the size of buffer buf[5] and the answer is 1-AAAA. Is this the best solution?"
Best is subjective, so I don't know.
Is this a correct solution? Yes, because strings are NUL-terminated (i.e., terminated with a byte of '\0', or 0), which means that buf must be big enough to hold four 'A' characters plus the terminating zero.
Since you have no control of where 'i' is placed in memory relative to 'buf', the strcpy() could have overwritten part of 'i' and caused the wrong result you reported.