First, the question
Have such a problem:
#include"stdio.h"intMain () {Charword1[8]; Charword2[8]; scanf ("%s", word1); scanf ("%s", Word2); printf ("word1=%s# #word2 =%s\n", Word1, Word2); return 0;}
Run the code and enter:
12345678 12345678
After that, why the output is:
word1=# #word2 =12345678
Where's word1?
Second, analysis
Since the C language local simple variable is present in the stack, the stack is advanced, so the variables defined first are at the bottom of the stack. After entering Word1, the in-memory variables are as follows:
As we can see, B8 has exceeded the range of character arrays defined by Word1.
When Word2 is entered, the in-memory variable becomes this:
Since only A8 to AF a total of 8 address space (because the last one to put the string end flag, so the actual can only use A8 to AE), but entered 8 characters, so that the end of the string is written to the next memory address (that is, B0).
Third, verification
#include"stdio.h"intMain () {Charword1[8]; Charword2[8]; scanf ("%s", word1); scanf ("%s", Word2); intCount =8; inti; printf ("\nword1 Begin addr =%p\n", word1); for(i=0; i<count;i++) {printf ("word1[%d]=%c addr=%p\n", I, Word1[i], &Word1[i]); } printf ("\ n-------------------------------\ n"); printf ("word2 Begin addr =%p\n", Word2); for(i=0; i<count;i++) {printf ("word2[%d]=%c addr=%p\n", I, Word2[i], &Word2[i]); } printf ("\ n-------------------------------\ n"); printf ("word1=%s# #word2 =%s\n", Word1, Word2); printf ("0x0028feb8=%c\n", *(int*)0x0028feb8); return 0; }
Operating effect:
C-language string memory allocation small note