如何让它不共享相同的内存

Wei*_*ida 0 c

#include <stdio.h>
typedef struct TESTCASE{
    char *before; 
}ts;
int main(void) {
     ts t[2] = {{"abcd"}, 
                {"abcd"}};
     t[0].before[0] = t[0].before[2] = t[0].before[3] = 'b';
     printf("%s - %s\n", t[0].before, t[1].before);
     return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出是

bbbb - bbbb

我在Cygwin中用gcc编译

cc -g test.c -o test

我的问题是,使用什么编译选项,我可以收获bbbb - abcd的结果?

Kar*_*ath 5

你不应该写字符串,它们是"不可变的",写入它会导致未定义的行为.

因此,编译器可以为两个字符串使用相同的位置.

提示:strdup() - 它在C中做了什么?