1

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!!!!!!!

2
  • 1
    You have five pointers. Where do they point? Nowhere. You must allocate some space. Commented Nov 8, 2020 at 3:29
  • Have a look at the function malloc but make sure you check the return value for errors. You should do that for fgets too. Commented Nov 8, 2020 at 3:38

1 Answer 1

2

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;
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

You could also statically allocate some space like char array[5][100];.
@DanielWalker, yes we could , since OP using pointers, so suggested that way.
@klutt, you are right, i just wrote the array of 5 pointers as 5 pointers to 5 arrays, not sure if OP understands if i say array of pointers, i could correct though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.