我正在尝试 C 中的字符串数组。我有一个字符串字典数组,我将单词添加到该数组中,然后打印出该数组以查看它是否有效。正如我认为的那样,输出可以打印数组中的单词。但是我收到了一些我无法修复的警告。
// 20 word dictionary
#define ROWS 20
#define WORD_LENGTH 10
char dictionary[ROWS][WORD_LENGTH];
void add_word(char **dict, int index, char *word) {
dict[index] = word;
}
char *get_word(char **dict, int index) {
return dict[index];
}
void print_dictionary(char **dict) {
int i;
for (i = 0; i < 20; i++) {
printf("%d: %s\n", i, get_word(dict, i));
}
}
void test_dictionary() {
add_word(dictionary, 0, "lorem");
add_word(dictionary, 1, "ipsum");
print_dictionary(dictionary);
}
int main() {
test_dictionary();
}
编译它的输出是,
p5.c: In function ‘test_dictionary’:
p5.c:54:2: warning: passing argument 1 of ‘add_word’ from incompatible pointer type [enabled by default]
p5.c:38:6: note: expected ‘char **’ but argument is of type ‘char (*)[10]’
p5.c:55:2: warning: passing argument 1 of ‘add_word’ from incompatible pointer type [enabled by default]
p5.c:38:6: note: expected ‘char **’ but argument is of type ‘char (*)[10]’
p5.c:57:2: warning: passing argument 1 of ‘print_dictionary’ from incompatible pointer type [enabled by default]
p5.c:46:6: note: expected ‘char **’ but argument is of type ‘char (*)[10]’
我尝试将 **dict 更改为 dict[ROWS][WORD_LENGTH] 没有太大区别。你们能解释一下如何声明这个字典参数吗?谢谢。
编辑:我的编译器标志是,CFLAGS = -Wall -g。
Edit2:将声明更改为,
void add_word(char dict[][WORD_LENGTH], int index, char *word) {
dict[index] = word;
}
char *get_word(char dict[][WORD_LENGTH], int index) {
return dict[index];
}
void print_dictionary(char dict[][WORD_LENGTH]) {
int i;
for (i = 0; i < 20; i++) {
printf("%d: %s\n", i, get_word(dict, i));
}
}
这会产生编译错误,
p5.c: In function ‘add_word’:
p5.c:42:14: error: incompatible types when assigning to type ‘char[10]’ from type ‘char *’
make[1]: *** [p5] Error 1
谢谢你的帮助。
啊! 弄清楚了!。由于它是一个指针,我需要按照@Jack 的建议使用 strcpy 。
void add_word(char dict[][WORD_LENGTH], int index, char *word) {
/*dict[index] = word;*/
strcpy(dict[index], word);
}
谢谢大家!