-1

I'm trying to pass an array of strings to another function and have it modified there. Here is where I declare the array and the declaration of the other function. (Effectively what I am doing is taking a string of chars, and sorting them into words into the array of strings, throwing out the whitespace). The sizes of the array are simply due to instructions for what I am working on. "strInput" is a the large array of chars I will be "cleaning"

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

Then later I declare:

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

This is giving me a warning.

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]);

I've tried a few different ways of passing it, but from what I see im passing a pointer to a two-dimensional array, and its asking for a pointer to a two-dimensional array. I am unsure why its invalid.

bock.steve
  • 221
  • 2
  • 12
  • You char array is basically a pointer, so when you pass it to another function, you basically pass it by reference. That means you only have to use char* cleaned instead of using the index as you have done there in the function parameter. – Mustakimur Khandaker Feb 19 '18 at 02:11
  • so you can use this void func(char* s, char cleaned[][21]){ } when use call as func(strInput, cleaned); – Mustakimur Khandaker Feb 19 '18 at 02:15
  • Possible duplicate of [How to pass 2D array (matrix) in a function in C?](https://stackoverflow.com/questions/3911400/how-to-pass-2d-array-matrix-in-a-function-in-c) – Mark Benningfield Feb 19 '18 at 02:20

1 Answers1

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

and call it like this

cleanInput("", cleaned);

But you might not now how many rows you have. I'd do

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

and call it:

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

This outputs:

word on row 0: hello
word on row 1: world
word on row 23: Bye
...
Pablo
  • 13,271
  • 4
  • 39
  • 59