我正在做一个练习,其中字符指针数组用作存储单词的方式。我不明白为什么我不能使用“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
是指向字符串文字的指针数组。
在这个声明中
strcpy(dict[1],newWord1);
您正在尝试将一个字符串文字复制到另一个字符串文字中。
字符串文字在 C 和 C++ 中是不可修改的。任何修改 strig 文字的尝试都会导致程序出现未定义的行为。
来自 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.
如果要在其元素中复制字符串文字,或者动态分配字符数组的一维数组,则应声明一个二维字符数组。
程序可以如下所示
#include <stdio.h>
#include <string.h>
#define N 9
size_t numberOfWordsInDict( char dict[][N] )
{
size_t n = 0;
while ( *dict[n] ) ++n;
return n;
}
void printDict( char dict[][N] )
{
printf("Dictionary:\n");
size_t n = numberOfWordsInDict( dict );
if ( n == 0 )
{
printf("The dictionary is empty.\n");
}
else
{
for ( size_t i = 0; i < n; i++ )
{
printf( "- %s\n", dict[i] );
}
}
}
int main(void)
{
char dict[10][9] =
{
"aap", "bro ", "jojo", "koe", "kip", "haha", "hond", " drop"
};
char *newWord1 = "hoi";
printDict(dict);
strcpy(dict[1], newWord1);
printDict(dict);
return 0;
}
程序输出为
Dictionary:
- aap
- bro
- jojo
- koe
- kip
- haha
- hond
- drop
Dictionary:
- aap
- hoi
- jojo
- koe
- kip
- haha
- hond
- drop
或者您可以使用可变长度数组。
请记住,根据 C 标准,不带参数的函数 main
应声明为
int main( void )