简体   繁体   中英

How to pass a variable size 2-D array to a C function

This is something that is explained in multiple places on the internet, but for some reason the previously explained solutions do not seem to be working for me I have an array of strings and I would like to pass the string array to a function that will print the array in a specific format. The implementation is shown below, where cols represents the number of columns to print, and length represents the number of strings in the array. The function should print the strings to column col and then continue printing on the next line.

#include <stdio.h>

void print_string_vec(size_t cols, size_t length, char vec[][length]) {
    size_t rows;
    size_t temp = length;
    size_t ncols = cols;
    size_t index = 0;
    if (length % cols == 0) rows = length / cols;
    else rows = (length / cols) + 1;

    printf("[ ");

    for (size_t i = 0; i < rows; i++) {
        if (temp <= cols) ncols = temp - 1;
        for (size_t j = 0; j < ncols; j++) {
            printf("%s, ", vec[index]);
            index++;
        }
        temp -= ncols;
        if (temp == 1) break;
        printf("\n");
        printf("  ");
    }
    printf("%s ", vec[length - 1]);
    printf("]\n");
}

int main() {
    char a[][10] = {{"First"}, {"Second"}, {"Third"}, {"Fourth"},
                    {"Fifth"}, {"Sixth"}, {"Seventh"}, {"Eight"},
                    {"Nine"}, {"Tenth"}};
    print_string_vec(5, 10, a);
}

I am expecting the following output

[ First, Second, Third, Fourth, Fifth,
  Sixth, Seventh, Eighth, Ninth, Tenth ]

However this consistently fails in compile time with the following warning;

error: use of parameter outside function body before `]` token

Which indicates that it has a problem with passing a variable length to the muti-array instantiation. If I replace this variable with 20 as a hard coded variable, it works fine, but then I have hard-coded a function to only work with one size array. From what I can read this is an issue with compilers that are not C99 compliant, but mine is. Any thoughts or suggestions would be appreciated. I am using gcc 12.1.0 and CMake to build the executable(s). I have specified C99 and later versions as the minimum build type and I get the same results.

You are missing a ; after print_string_vec(5, 10, a) . And to compile the program you also need to include this header:

#include <stdio.h>

Your program then generates the following output:

[ First, , Second, , Third, 
  , Fourth, , Fifth,  ]

You declare a[][20] but use in the function as a[][10] . If you change the declaration:

char a[][10] = { ... };

It now gets you the expected output.

Here is a more straight forward implementation:

void print_string_vec(size_t cols, size_t length, char vec[][length]) {
    enum { FIELD, LINE, LAST_LINE };
    const char *sep[] = {
        [FIELD] = ", ",
        [LINE] = ",\n  ",
        [LAST_LINE] = " "
    };
    printf("[ ");
    for(size_t i = 0; i < length; i++) {
        printf("%s%s",
            vec[i],
            sep[
                 !i || (i + 1) % cols ?
                     FIELD :
                     i + 1 < length ?
                         LINE :
                         LAST_LINE
            ]);
    }
    printf("]\n");
}

int main() {
    char a[][10] = {{"First"}, {"Second"}, {"Third"}, {"Fourth"},
                    {"Fifth"}, {"Sixth"}, {"Seventh"}, {"Eight"},
                    {"Nine"}, {"Tenth"}};
    print_string_vec(5, 10, a);
}

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