2017-12-22 14 views
0

Stephen Kochanの "Programming in C"の第10章の最後の演習では、structsの配列をアルファベット順にソートする関数を記述しています。構造体の配列を関数に渡す

構造体は、辞書を模倣形態

struct entry 
{ 
    char word[15]; 
    char definition[50]; 
}; 

を有しています。これらstructsの配列は、この

const struct entry dictionary[10] = 
{ 
    {"agar",  "a jelly made from seaweed"}, 
    ..., 
    ..., 
    {"aerie",  "a high nest"} 
} 

ようになりstruct entryの定義はdictionaryがメインであり、グローバルです。

私はentriesdictionary内の要素の数であるとアルファベット順にdictionarySort

void dictionarySort(struct entry dictionary[], int entries) 

と呼ばれるこの辞書を並べ替えることになっている機能を書きました。 mainでは、私は関数を宣言し、

dictionarySort(dictionary, 10); 

でそれを呼び出す今、私は取得エラー関数の

warning: passing argument 1 of ‘dictionarySort’ discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]

関数呼び出しの

note: expected ‘struct entry *’ but argument is of type ‘const struct entry *’ void dictionarySort(struct entry dictionary[], int entries)

ヘッダ。

私はPassing an array of structs in Cを見つけて、受け入れられた答えに従いましたが、それでも動作しません。私はまだ彼らが本に紹介されていないので、私はポインタについて学んでいないことに注意してください。

答えて

3

justeは、配列宣言でconstを削除します。

コンパイラconstの場合、この変数のスタックに割り当てられたメモリ領域は読み取り専用であるため、関数はその変数を変更すべきではありません。

+0

この回答は普遍的ではありません。この場合正しいですが、多くの場合、正しい答えは "関数に' const'を追加することです。可能であれば、それを好むべきです。 –

+0

それは、ヘッダーが 'const'であると定義しているので、関数内で渡された引数を変更できないということではありませんか? – jruota

関連する問題