C 为什么在函数中作为参数传递字符数组并尝试在函数内部修改会显示分段错误?
我声明了一个char变量数组,如下所示:C 为什么在函数中作为参数传递字符数组并尝试在函数内部修改会显示分段错误?,c,arrays,pointers,char,constants,C,Arrays,Pointers,Char,Constants,我声明了一个char变量数组,如下所示: char word[256]; char plural[256]; scanf("%s",&word); strcpy(plural,word); void pluralize(word,plural); 它在main函数中获取输入,并复制到复数变量,如下所示: char word[256]; char plural[256]; scanf("%s",&word); strcpy(plural,word); void plura
char word[256];
char plural[256];
scanf("%s",&word);
strcpy(plural,word);
void pluralize(word,plural);
它在main
函数中获取输入,并复制到复数变量,如下所示:
char word[256];
char plural[256];
scanf("%s",&word);
strcpy(plural,word);
void pluralize(word,plural);
我提供的输入是“Baby”
main方法调用另一个函数时,将两个变量作为参数传递,如下所示:
char word[256];
char plural[256];
scanf("%s",&word);
strcpy(plural,word);
void pluralize(word,plural);
下面是我想用复数方法做的事情:
void pluralize(char word[], char plural[]){
char textToBeAdded[] = "IES";
int i = strlen(plural);
plural[i-1] = '\0';
plural = strcat(plural, textToBeAdded);
printf("Word is %s and plural is %s", word, plural);
printf("\nRule is 1\n");
}
我没有使用
char*
和char[]
,所以应该可以修改。但它显示了一个分段运行时错误。为什么我做错了,我做错了什么?这句话有一个问题:
scanf("%s",&word);
word
是char
s的数组。因此,要读懂它,您只需:
scanf("%s",word);
显示一个,而不仅仅是几个代码片段。您作为输入提供了什么?它应该足够小,以适合字符数组。此外,如果
mulral
为空,mulral[i-1]='\0'代码>此行是未定义的行为。我正在使用strcpy将单词复制为复数。单词的输入是“Baby”。此外,请考虑情况下不为空的情况。为什么我要在这里使用空字符?