简体   繁体   English

如何从C中的输入读取字符串数组并传递给函数?

[英]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.我希望能够在 C 中创建一个字符串数组,并将该数组传递给 PrintStuff 函数。 I don't want to change my parameters to PrintStuff, but still make it work.我不想将我的参数更改为 PrintStuff,但仍要使其工作。 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]将“char *[5]”传递给“const char **”类型的参数会丢弃嵌套指针类型中的限定符 [-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] .首先了解什么是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*的 5 个指针的数组,因此在使用它们之前,每个指针都需要内存。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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