use*_*974 13 c string replace character
我正在尝试在C上做一些非常基本的事情,但我一直遇到分段错误.我想做的就是用一个不同的字母替换一个单词的字母 - 在这个例子中用l代替l.任何人都可以帮助解释我哪里出错了吗?这应该是一个非常基本的问题我想,我只是不知道它为什么不起作用.
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
char *string1;
string1 = "hello";
printf("string1 %s\n", string1);
printf("string1[2] %c\n", string1[2]);
string1[2] = 'L';
printf("string1 %s\n", string1);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我得到了我的输出
string1 hello
string1 [2] l
分段错误
谢谢!
cni*_*tar 16
Run Code Online (Sandbox Code Playgroud)string1 = "hello"; string1[2] = 'L';
你不能改变字符串文字,它是未定义的行为.试试这个:
char string1[] = "hello";
Run Code Online (Sandbox Code Playgroud)
或者可能:
char *string1;
string1 = malloc(6); /* hello + 0-terminator */
strcpy(string1, "hello");
/* Stuff. */
free(string1);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37748 次 |
| 最近记录: |