我正在做一个练习,其中一个字符指针数组作为存储单词的一种方式。我不明白为什么我不能使用'strcpy'将单词'hoi'复制到主函数中数组的第二个元素。当我编译代码时,我在CodeBlocks中收到'程序已停止工作'的消息。不能从C中的strcpy指针数组中复制字符串?
函数'numberOfWordsInDict'和'printDict'正常工作。
在此先感谢。
int numberOfWordsInDict(char **dict)
{
int i, cnt = 0;
for(i = 0; i < 10; i++)
{
if(dict[i] != NULL)
{
cnt++;
}
}
return cnt;
}
void printDict(char **dict)
{
int i = 0;
printf("Dictionary:\n");
if(numberOfWordsInDict(dict) == 0)
{
printf("The dictionary is empty.\n");
} else
{
for(i = 0; i < 10; i++)
{
printf("- %s\n", dict[i]);
}
}
}
int main()
{
char *dict[10] = {
"aap", "bro ", "jojo", "koe", "kip",
"haha", "hond", " drop", NULL,NULL};
char *newWord1 = "hoi";
printDict(dict);
strcpy(dict[1], newWord1);
printDict(dict);
return 0;
}
'快译通[1]'指向一个字符串的第一个字符。修改'strcpy(dict [1],newWord1)'这样的字符串文字会导致未定义的行为。 – Peter
非常感谢大家! –
这是一个令人难以置信的常见问题。如果您在“字符串”下面查看[Stack Overflow C FAQ](https://stackoverflow.com/tags/c/info),有几个规范的帖子可用于进一步阅读/重复关闭。 – Lundin