【发布时间】:2018-01-18 20:01:37
【问题描述】:
我正在做一个练习,其中字符指针数组用作存储单词的一种方式。我不明白为什么我不能使用“strcpy”将单词“hoi”复制到主函数中数组的第二个元素。当我编译代码时,我在 CodeBlocks 中收到消息“程序已停止工作”。
函数“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;
}
【问题讨论】:
-
dict[1]指向字符串文字的第一个字符。修改strcpy(dict[1], newWord1)所做的字符串文字会产生未定义的行为。 -
非常感谢大家!
-
这是一个非常常见的常见问题解答。如果您查看“字符串”下方的Stack Overflow C FAQ,则有几个规范帖子可用于进一步阅读/关闭重复。
标签: c undefined-behavior strcpy string-literals