更改char数组的值

Can*_*ncü 4 c arrays pointers

char* foo = (char*) malloc(sizeof(char)*50); foo = "testing";
Run Code Online (Sandbox Code Playgroud)

在C中,我可以看到该字符串的第一个字符:

printf("%c",foo[0]);
Run Code Online (Sandbox Code Playgroud)

但是当我试图改变这个价值时:

foo[0]='f'
Run Code Online (Sandbox Code Playgroud)

它在运行时出错.

如何更改动态分配的char数组值?

Hog*_*gan 8

您正在设置foo指向字符串文字("testing")而不是您分配的内存.因此,您尝试更改常量的只读内存,而不是已分配的内存.

这是正确的代码:

char* foo = malloc(sizeof(char)*50);
strcpy(foo,"testing");
Run Code Online (Sandbox Code Playgroud)

甚至更好

cont int MAXSTRSIZE = 50;
char* foo = malloc(sizeof(char)*MAXSTRSIZE);
strncpy(foo,"testing",MAXSTRSIZE);
Run Code Online (Sandbox Code Playgroud)

防止缓冲区溢出漏洞.

  • 不要施放你的malloc.char*foo = malloc(sizeof(char)*MAXSTR); (3认同)