0

An exercise at the end of chapter 10 of "Programming in C" by Stephen Kochan says to write a function that sorts an array of structs in alphabetical order.

The struct has the form

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

which mimics a dictionary. An array of these structs would look like this

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

The definition of struct entry is global, dictionary is in main.

I wrote a function that is supposed to sort this dictionary alphabetically called dictionarySort

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

with entries being the number of elements in dictionary. In main I declare the function and call it with

dictionarySort(dictionary, 10);

Now I get the errors

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

for the function call and

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

for the function header.

I found Passing an array of structs in C and followed the accepted answer but it still does not work. Note that I have not learned about pointers as they have not been introduced in the book yet.

jruota
  • 147
  • 2
  • 8

1 Answers1

3

juste drop the const in your array declaration.

for the compiler const mean that the memory space allocated on the stack for this variable is read-only, so your function should not modify it.

alkaya
  • 145
  • 6
  • Note that this answer is not universal. It’s correct in this case, but in a lot of cases the correct answer is “add `const` to the function”. You should prefer that, if possible. – Daniel H Dec 22 '17 at 18:31
  • Would that not mean that I cannot change the passed argument within the function as the header defines it to be a `const`? – jruota Dec 29 '17 at 17:19