在c中修改不同函数中的字符串数组

时间:2018-02-19 01:56:45

标签: c arrays pointers warnings

我正在尝试将一个字符串数组传递给另一个函数并在那里进行修改。这是我声明数组和其他函数声明的地方。 (实际上我正在做的是获取一串字符,并将它们排序成字符串数组,抛出空格)。阵列的大小仅仅取决于我正在处理的内容。 “strInput”是我将“清理”的大量字符

char cleaned[151][21];
cleanInput(strInput, &cleaned);

然后我宣布:

void cleanInput(char* s, char* cleaned[151][21])
{
  //do stuff
}

这给了我一个警告。

warning: passing argument 2 of ‘cleanInput’ from incompatible pointer 
type [-Wincompatible-pointer-types]
cleanInput(strInput, &cleaned);


note: expected ‘char * (*)[21]’ but argument is of type ‘char (*)[151][21]’
void cleanInput(char* s, char* cleaned[151][21]);

我尝试了几种不同的传递方式,但是从我看到的我传递一个指向二维数组的指针,并且它要求指向二维数组的指针。我不确定为什么它无效。

1 个答案:

答案 0 :(得分:0)

void cleanInput(char* s, char (*cleaned)[21])
{
    // stuff
}

并像这样称呼它

cleanInput("", cleaned);

但是你现在可能没有多少行。我做了

void cleanInput(char* s, char (*cleaned)[21], size_t rows)
{
    for(size_t i = 0; i < rows; ++rows)
    {
        if(**(cleaned + i) != 0)
            printf("word on row %zu: %s\n", i, *(cleaned + i));
    }
}

并称之为:

char cleaned[151][21];
memset(cleaned, 0, sizeof cleaned);
strcpy(cleaned[0], "hello");
strcpy(cleaned[1], "world");
strcpy(cleaned[23], "Bye");
cleanInput("", cleaned, sizeof cleaned / sizeof *cleaned);

输出:

word on row 0: hello
word on row 1: world
word on row 23: Bye
...
相关问题