Hi,
I have put together a small program that is supposed to sort strings into alphabetical order. However, I'm having a problem using "const".
The program uses a variable in main() which is passed as an argument to various functions. As these functions are not allowed to change the value of the (function) parameter that matches the argument, I have "marked" this parameter as const. However the gcc compiler doesn't like this and generates the following output.
Code:
prog8_4.c: In function ‘main’:
prog8_4.c:49:13: warning: passing argument 1 of ‘str_sort’ from incompatible pointer type [-Wincompatible-pointer-types]
49 | str_sort(pS, str_count); // Sort strings
| ^~
| |
| char **
prog8_4.c:13:15: note: expected ‘const char **’ but argument is of type ‘char **’
13 | void str_sort(const char **, size_t); // Sorts an array of strings
| ^~~~~~~~~~~~~
Here is the function prototype.
Code:
void str_sort(const char **, size_t); // Sorts an array of strings
Here is main().
Code:
int main(void)
{
size_t pS_size = INIT_NSTR; // count of pS elements
char ** pS = calloc(pS_size, sizeof(char *)); // Array of string pointers
if(!pS)
{
printf("Failed to allocate memory for string pointers.\n");
exit(1);
}
char **pTemp = NULL; // Temporary pointers
size_t str_count = 0; // Number of strings read
char *pStr = NULL; // String pointer
printf("Enter one string per line. Press Enter to end:\n");
while((pStr = str_in()) != NULL)
{
if(str_count == pS_size)
{
pS_size += NSTR_INCR;
if(!(pTemp = realloc(pS, pS_size * sizeof(char *))))
{
printf("Memory allocatio for array of strings failed.\n");
return 2;
} // end inner if()
pS = pTemp;
} // end outer if()
pS[str_count++] = pStr;
} // end while()
str_sort(pS, str_count); // Sort strings
str_out(pS, str_count); // Output strings
free_memory(pS, str_count); // Free all heap memory
return 0;
} // end main()
Although the compiler generates the same error for functions str_sort() and str_out(), I will only show the code for str_sort() for brevity.
Code:
void str_sort(const char ** p, size_t n)
{
bool sorted = false; // Strings sorted indicator
while(!sorted) // Loop until there are no swaps
{
sorted = true; // initialize to indicate no swaps
for(int i = 0; i < n - 1; ++i)
{
if(strcmp(p[i], p[i + 1]) > 0)
{
sorted = false; // indicate we are out of order
swap(&p[i], &p[i + 1]); // Swap the string addresses
} // end if()
} // end for()
} // end while()
} // end str_sort()
I thought this was the right way to use const but with the compiler objecting I am now not so sure. I have read through
Code:
https://stackoverflow.com/questions/14401856/how-do-i-best-use-the-const-keyword-in-c
but this seemed merely to agree with what I was already doing and so, sadly, did not help.
To compile this small program I use the following in Konsole.
gcc prog8_4.c -std=c11 -Wall -ggdb -o prog8_4
What am I not understanding about this use of const ?
Stuart