Misunderstanding of using string array to read strings in C Language

Source: Internet
Author: User

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.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.