我工作在C程序和函数带有三个参数,将与另一个字符的字符串替换字符。那么大部分的它工作得很好,但尝试执行代码的这一部分时,我得到的连接错误:STR [POS] = CH ;.错误说:“访问冲突写入位置0x0133585B。”
void kstrput(char *str, size_t pos, char ch)
{
if(pos > strlen(str))
{
abort();
}
str[pos] = ch;
}
的主要部分:
char *kstr = "hello";
int pos = 3;
char s = '\0';
printf("\n Enter a character ");
scanf("%c", &s);
kstrput(kstr,pos,s); // calling the kstrput function
printf("\n After kstrput: %s",kstr); //printing the struct to check value of the string
"hello"
是恒定的(不能修改),并可能是(也许是)存储在只读存储器。
指向它的正确方法是使用类型const char *
的指针。你需要在你的情况做的就是定义char
的阵列并初始化它为“Hello”:
char kstr[] = "hello";
还要注意的是,在kstrput
如果pos
等于strlen(str)
那么它将覆盖指示字符串末尾的'\0'
。更好地利用:
if(pos >= strlen(str))
“访问冲突写入位置0x0133585B。”
你做
{
int pos = 3;
...
char *kstr = "hello";
...
kstrput(kstr,pos,s); // calling the kstrput function
}
void kstrput(char *str, size_t pos, char ch)
{
str[pos] = ch;
...
}
在str[pos] = ch;
POS估价3是有效的索引,但str是字符串“你好”,一个字符串文字不能被修改
这条线在函数void kstrput(字符* STR,为size_t POS,炭CH)
if(pos > strlen(str))
应改为
if(pos >= strlen(str))