简体   繁体   中英

Why does x[2] reassign the y value as well? And how do I fix this

#include <stdio.h>
#include <cs50.h>

int main(void)
{

    string y, x;
    y = x = get_string();

    x[2] = '\0';

    printf("%s", x);
    printf("%s", y);

} 

If input is abcdef . Output for this code is abab . Why is it not ababcdef .

That's because y and x pointing to the same string returned by get_string .

get_string :

Reads a line of text from standard input and returns it as a string ( char * ), sans trailing newline character. [...]

You assigned the string the NUL terminator so printf will end printing when it finds it. Also x and y point to same string literal. Try this code out to understand what is happening:

x[2] = '\0';

for(int idx = 0; idx < 6; idx++ )
{
    if( x[idx] == '\0')
        printf("NUL");
    else
        printf("%c", x[idx]);
}
    printf("\n");
for(int idx = 0; idx < 6; idx++ )
{
    if( y[idx] == '\0')
        printf("NUL");
    else
        printf("%c", y[idx]);
}

My guess is that get_string() gives you a pointer on the string. So when you assigning the value in x and y you are actually pointing to a string and not storing it. So when you change something you are affecting the string itself. To fix it you should use strcpy(); to copy the string so that you are not using pointer references.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM