简体   繁体   中英

How to read a string array from input in C and pass to function?

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

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM