gpt4 book ai didi

arrays - 初始化从指针目标类型中丢弃 ‘const’ 限定符

转载 作者:行者123 更新时间:2023-12-03 23:39:53 28 4
gpt4 key购买 nike

我有一个包含字符名称的数组结构。我想使用 qsort 按字母顺序对它们进行排序,但是我一直收到一条错误消息,说“初始化丢弃了指针目标类型中的‘const’限定符”。我相信我的 cmpmi() 函数和 qsort 参数是正确的。任何帮助是极大的赞赏!
我的错误是:

gcc -std=gnu11 -Werror -Wall -o main main.c -lm -g
main.c: In function ‘compmi’:
main.c:18:25: error: initialization discards ‘const’ qualifier from pointer target type [-Werror=discarded-qualifiers]
const student_t **p1 = a;
^
main.c:19:25: error: initialization discards ‘const’ qualifier from pointer target type [-Werror=discarded-qualifiers]
const student_t **p2 = b;
^
cc1: all warnings being treated as errors
makefile:2: recipe for target 'main' failed
make: *** [main] Error 1

这是我的 qsort 功能:
int compmi(const void *a, const void *b)
{
const student_t **p1 = a;
const student_t **p2 = b;
return strcmp((*p1)->name, (*p2)->name);
}
代码:
int main(int argc, char **argv) {
unsigned numrecords;
int i = 0;
int length_multiplier = 1;
char *lettergrade;
//char *input = NULL;
//char *pItem;

student_t **students = NULL;
// OPENS THE FILE IN BINARY
FILE *input_file;
input_file = fopen("input.bin", "rb");
// READS THE NUMBER OF RECORDS
fread(&numrecords, sizeof(u_int32_t), 1, input_file);

// LOOPING THROUGH EACH ENTRY
for(i = 0; i <= numrecords; i++)
{
// ALLOCATES MEMORY
students = realloc(students, sizeof(student_t *) * length_multiplier);
students[i] = malloc(sizeof(student_t));

students[i]->name = malloc(sizeof(student_t)* 20);
fread(students[i]->name, sizeof(student_t), 20, input_file);//READ NAME
fread(&students[i]->gpa, sizeof(student_t), 1, input_file); // READ GPA
fread(&students[i]->age, sizeof(u_int32_t), 1, input_file);// READ AGE

length_multiplier++;

}
//SORTING WITH QSORT
qsort(*students, numrecords, sizeof(student_t *), compmi);

// PRINTING OUTPUT
for(i = 0; i < length_multiplier - 2 ; i++)
{
printf("%i of %d:\n", i + 1, numrecords);
printf("Name: %s\n", students[i]->name);
//printf("UPDATED GPA USE THIS: %.1f\n", students[i]->gpa);
printf("GPA: %.1f \n", students[i]->gpa);
printf("Age: %i\n", students[i]->age);
printf("\n");
}

// FREEING MEMORY
for(i = 0; i < length_multiplier; i++)
{
free(students[i]);

}
free(students);
fclose(input_file);

return 0;
}

最佳答案

变量 a指向 const限定类型,但 p1不指向 const类型(但它指向的是什么)。您需要添加 const *之间s。

int compmi(const void *a, const void *b)
{
const student_t * const *p1 = a;
const student_t * const *p2 = b;
return strcmp((*p1)->name, (*p2)->name);
}

关于arrays - 初始化从指针目标类型中丢弃 ‘const’ 限定符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66510293/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com