Kyl*_*ven 1 c arrays string replace character
如何让我的replace_char函数正常工作?
我在下面的函数中尝试它的方式使用Ubuntu中的gcc返回分段错误.
我尝试过其他方法,但每次尝试更改值时,都会出错.
int main (void)
{
char* string = "Hello World!";
printf ("%s\n", string);
replace_char(string, 10, 'a');
printf ("%s\n", string);
}
void replace_char(char str[], int n, char c)
{
str[n] = c;
}
Run Code Online (Sandbox Code Playgroud)
你的replace_char功能没有任何问题.问题是您正在尝试修改字符串文字("Hello World!")并且这是未定义的行为.尝试制作字符串的副本,如下所示:
char string[] = "Hello World!";
Run Code Online (Sandbox Code Playgroud)
编辑
要获得编辑的"建议" string,您可以在适当的位置编辑指针:
void replace_char(char*& str, int n, char c)
{
str = strdup(str);
str[n] = c;
}
int main()
{
char* string = "Hello World!";
string = replace_char(string, 10, 'a');
// ...
free(string);
}
Run Code Online (Sandbox Code Playgroud)
请注意,您现在必须记住free在调用它之后调用字符串.相反,我建议您执行我之前建议的操作:如果需要,将文字包装在strdup中.这样你就不会一直承担分配副本的费用(只在必要时).
问题是"Hello World"是一个const 文字 char数组.
const char* conststr = "Hello World!";
char * string = strdup(conststr);
Run Code Online (Sandbox Code Playgroud)
我认为问题将会消失
Explanation: 编译器可以在(只读)数据段中分配字符串文字.转换为char*(与const char*相反)实际上无效.如果您使用例如
gcc -Wall test.c
Run Code Online (Sandbox Code Playgroud)
你会收到警告.
在这里观察(因为它是未定义的行为)编译器可以在这种情况下做有趣的事情:
http://ideone.com/C39R6显示程序不会"崩溃",但默认无法修改字符串文字,除非复制了字符串.
因人而异.使用-Wall,如果可以的话,使用某种lint,并进行单元测试:){