我环顾四周,在其他问题中找不到我的问题的解决方案。由于某种原因,当我运行程序时出现段错误,这似乎是因为我正在更改给定的字符串。我尝试将指针传递给 char 指针并对其进行编辑,但无济于事。
我得到什么:
之前:胡安巴布罗 段错误(核心转储)
我的代码:
void rm_char(char* word, int pos){
printf("before: %s\n", word);
int len = strlen(word);
int i;
i = pos;
while(word[i+1] != '\0'){
word[i] = word[i+1];
i++;
}
word[i] = '\0';
printf("after: %s\n", word);
}
int main(void){
rm_char("juanpablo", 2);
}
最佳答案
来自 C 标准(6.4.5 字符串文字)
7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.
要避免错误,您可以调用如下函数
char s[] = "juanpablo";
rm_char( s, 2 );
考虑到第二个参数最好使用 size_t
类型而不是 int
类型,并且声明的变量 len
如下
int len = strlen(word);
未在函数中使用。
函数应该这样声明
char * rm_char(char* word, size_t pos);
这是一个演示程序
#include <stdio.h>
#include <string.h>
char * rm_char(char *word, size_t pos)
{
size_t n = strlen( word );
if ( pos < n )
{
//memmove( word + pos, word + pos + 1, n - pos );
do
{
word[pos] = word[pos+1];
} while ( word[pos++] );
}
return word;
}
int main(void)
{
char word[] = "juanpablo";
puts( word );
puts( rm_char( word, 2 ) );
return 0;
}
它的输出是
juanpablo
junpablo
关于编译器不允许我编辑传递的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47681043/