c - 为什么 x[2] 也重新分配 y 值?我该如何解决这个问题

标签 c variables cs50

#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);

} 

如果输入是abcdef。此代码的输出是 abab。为什么不是 ababcdef

最佳答案

那是因为 yx 指向 get_string 返回的同一个字符串。

get_string :

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

关于c - 为什么 x[2] 也重新分配 y 值?我该如何解决这个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43466635/

相关文章:

c - 如何在结构中存储当前系统日期?

java - 为什么proguard不混淆方法主体?

c - fopen 改变 C 中的变量值

CS50 Pset1 现金错误 "expected identifier or ' ('"含义?

c - 返回字符串而不是 int

c - 无法让子进程相互通信

结构中的 C 变量范围

c - 为弹丸运动获得错误的时间和高度值

带空格的 Bash 变量

ruby - 枚举期间正在修改数组