James M-Coates James M-Coates - 3 months ago 7
C Question

C - Pass Array of Strings as Function Parameter

I need to pass a pre-allocated array of strings as a function parameter, and strcpy() to each of the strings within the string array, as in this example:

static void string_copy(char * pointer[]) {

strcpy(pointer[0], "Hello ");

strcpy(pointer[1], "world");

}

int main(int argc, const char * argv[]) {

char my_array[10][100];

string_copy(my_array);

printf("%s%s\n", my_array[0], my_array[1]);

}


And the resulting printed string would be 'Hello world'.

How do I pass a pre-allocated string array and fill out each string within a function as shown above?

sps sps
Answer

When you are doing string_copy(my_array), you are passing a char (*)[100], i.e. pointer to char[100] array to your function. But your function is expecting a char *[], i.e. array of char pointers, because you have defined your function that way.

You can fix this by making changes so that your function (string_copy()) expects a char (*)[100], instead of a char *[].

For this, you can change your function definition as:

/* Your my_array gets converted to pointer to char[100]
   so, you need to change your function parameter
   from `char *pointer[]` to `char (*pointer)[100]` 
*/ 
/* static void string_copy(char *pointer []) */
static void string_copy(char (*pointer) [100])
{
    strcpy(pointer[0], "Hello ");
    strcpy(pointer[1], "world");
}

A different design would be to change in your main() function so that you are actually passing a char *[], which decays into a char ** - which is fine - to string_copy().

int main(int argc, const char * argv[]) {

    char my_array[10][100];
    int tot_char_arrs, i;
    char *char_arr_ptr[10];

    /* Get total number of char arrays in my_array */
    tot_char_arrs = sizeof(my_array) / sizeof(my_array[0]);

    // Store all char * 
    for (i = 0; i < tot_char_arrs; i++)
            char_arr_ptr[i] = my_array[i];

    /* Actually passing a char *[].
       it will decay into char **, which is fine
     */
    string_copy(char_arr_ptr);

    printf("%s%s\n", my_array[0], my_array[1]);
}
Comments