Stephen Kochan在“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
是主要的。
我写了一个函数,应该按字母顺序对这个字典进行排序,称为dictionarySort
void dictionarySort(struct entry dictionary[], int entries)
entries
是dictionary
中元素的数量。在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并按照接受的答案,但它仍然无法正常工作。请注意,我还没有学过指针,因为它们还没有在书中介绍过。
juste在数组声明中删除const。
对于编译器const意味着在此堆栈上为此变量分配的内存空间是只读的,因此您的函数不应修改它。