Reputation: 11
I have been stuck on this all day. I want to be able to create a string array in C, and pass that array to the PrintStuff function. I don't want to change my parameters to PrintStuff, but still make it work. Any help please?
void PrintStuff(const char **arr) {
for (int i = 0; i < 5; ++i) {
printf ("%s\n", arr[i]);
}
}
int main ()
{
//This works
//char * array[5] = { "this", "is", "a", "test", "megan"};
//This doesn't work
char * array[5];
for (int i=0;i<5;i++)
{
//scanf("%9s", array[i]);
fgets(array[i], 10, stdin);
}
Sort(array, 0, 5 - 1);
}
It doesn't do anything and I get this warning that says
passing 'char *[5]' to parameter of type 'const char **' discards qualifiers in nested pointer types [-Wincompatible-pointer-types-discards-qualifiers]
I've got no ideas what that means or how to fix it, HELP ME PLEASE!!!!!!!
Upvotes: 1
Views: 111
Reputation: 821
First Understand what is char* array[5]
.
that is nothing but array of 5 pointers to char*
, so you need memory for each pointer before you can use them.
char* array[5] = NULL;
int noe = sizeof(array) / sizeof (array[0]);
for(int a = 0; a < noe; a++) {
if( !(array[a] = malloc(BUFFER_SIZE))
printf("malloc failed at %d entry\n", a);
}
dont forget to free them when you are done using them
for(int a = 0; a < noe; a++) {
if(array[a]) {
free(array[a]);
array[a] = NULL;
}
}
Upvotes: 2