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);
}
みんな、ありがとう!