I have an array structs that hold char names. I want to sort them alphabetically using qsort however I keep getting an error message saying "initialization discards ‘const’ qualifier from pointer target type". I believe my cmpmi() function and qsort arguments are correct. Any help is greatly appreciated!
My error is:
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
This is my qsort function:
int compmi(const void *a, const void *b)
{
const student_t **p1 = a;
const student_t **p2 = b;
return strcmp((*p1)->name, (*p2)->name);
}
Code:
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;
}