繁体   English   中英

将结构数组传递给函数

[英]Passing array of structs to function

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是主要的。

我写了一个函数,该函数应该按字母顺序对这本字典进行排序,即字典

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

entriesdictionary中元素的数量。 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)

用于函数头。

我发现在C中传递结构数组并遵循接受的答案,但仍然无法正常工作。 请注意,由于尚未在本书中介绍指针,因此我还没有学到任何有关指针的知识。

只需将const放入数组声明中即可。

对于编译器const,意味着在堆栈上为此变量分配的内存空间是只读的,因此您的函数不应对其进行修改。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM