I recently encountered a very strange problem. I think I have to record it when I turn off my computer.
The main code is as follows:
int main(){ char* key[2]; scanf("%s", &key[0]); scanf("%s", &key[1]); printf("%s \n", &key[0]); return 0;}
To read the input string from the console, define an array of char * type, and the result is incorrect.
When input: whos who output: whoswho
When input: wwwwww dddddd output: wwwwdddddddd
I won't talk about the tangle. I have discussed it with my classmates for a long time and come to a conclusion (maybe wrong)
Char * occupies four bytes in CBecause the defined key is an array, assign a block to it during declaration.ContinuousMemory, soEach unit of the array key is fixed to four bytes..
In the first case, whos occupies exactly four bytes, and the final terminator (remember \ 0) is out of bounds in key [1, the data written into the key [1] memory address is overwritten, so the system does not know where the key [0] ends, and reads it all the time, until the final character of key [1] is met, a piece of key [1] is output.
The second case is similar. 6 w data cannot be stored in 4 bytes, and only the first four data records can be stored. The last two data records are transferred to key [1, data written into the key [1] memory address is overwritten. Although the next 6 d is out of the range, this array only has two lengths. key [I] only records the first address and does not record the end address, therefore, the 6 d occupies the memory of the next part of the 8-byte memory allocated for this array, so the complete output of the last string is complete.
Assume that the length of the key is defined as 2, but only one string is read, no matter how long it is, it can be completely output, because the cross-border part of the key is not overwritten.
Therefore, if the input string is larger than 4 bytes, only the last input string can be completely output.