c - char* 的可变二维数组作为 C 中的返回值

标签 c arrays pointers

我在尝试分配 char* 的二维数组并从函数返回它时遇到问题。

//my return type needs to change to something like (char*)[]?
char **readData( size_t numRows, size_t numCols )
{
    //I think this needs to chage to something like this:
    //char* (*data)[numRows] = malloc(sizeof(char*) * numCols );
    char **data = malloc( sizeof(char*) * numRows * numCols );

    for( size_t r=0; r < numRows; ++r ) {
        for(size_t c=0; c < numCols; ++c) {     
            data[r*numRows+c] = strdup( getString() );

            //I'd like this to be:
            //data[r][c] = strndup( getString() );
        }
    }

    return data;
}

int main()
{
    size_t rows = 5;
    size_t cols = 7;
    char **data = readData( rows, cols );

    if( data != NULL ) {

        for( int r=0; r < rows; ++r ) {
            for( int c=0; c < cols; ++c ) {
                printf( "[%i][%i] = %s\n", r, c, data[r*rows+c] );
                free(data[r*rows+c]);
                data[r*rows+c] = NULL;

                //I'd really like this to be:
                //printf( "[%i][%i] = %s\n", r, c, data[r][c] );
                //free(data[r][c]);
                //data[r][c] = NULL;
            }
        }

        free(data);
        data = NULL;
    }

    return 0;
}

我有两个问题:

1) 上面的代码不知何故被破坏了。当我不希望 printf 打印 NULL 时,它会打印 NULL。我一定是在某个地方搞砸了索引。

2) 我相信使用 C99,我可以使用更熟悉的 data[][] 表示法来索引二维指针数组。我对上面代码中的注释进行了更改,但我不知道将函数的返回类型设置为什么。如何更改我的程序以使用 data[][] 表示法?这可能是不可能的,因为我在编译时不知道任何一个数组维度。

我已经查看了以下堆栈溢出问题,但似乎仍然无法理解它: Why can't we use double pointer to represent two dimensional arrays?

How to return a two-dimensional pointer in C?

Why can't we use double pointer to represent two dimensional arrays?

最佳答案

您有一个二维字符串网格,因此您的数据结构是 char ***。各级数据动态分配。

datanumRows 行动态数组的句柄。每行 data[r] 都是一个动态数组 numCols 字符串的句柄;这些数组也必须显式分配。每个字符串 data[r][c] 都是动态字符数组的句柄,您可以通过 strdup 创建该数组。

所以你的代码可能看起来像:

char ***readData(size_t numRows, size_t numCols)
{
    char ***data = malloc(numRows * sizeof(*data));

    for (size_t r=0; r < numRows; ++r) {
        data[r] = malloc(numCols * sizeof(*data[r]));

        for(size_t c=0; c < numCols; ++c) {     
            data[r][c] = strdup(getString());
        }
    }

    return data;
}

int main()
{
    size_t rows = 5;
    size_t cols = 7;
    char ***data = readData(rows, cols);

    if (data != NULL) {
        for (int r = 0; r < rows; ++r) {
            for (int c = 0; c < cols; ++c) {
                printf("[%i][%i] = \"%s\"\n", r, c, data[r][c]);
                free(data[r][c]);
            }
            free(data[r]);
        }
        free(data);
    }

    return 0;
}

关于c - char* 的可变二维数组作为 C 中的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33572905/

相关文章:

C++ reinterpret_cast 一个整数

c++ - 删除数组只是偶尔失败

C 编程问题

c - 在 C 中访问大于 UINT_MAX*4 大小的内存?

c - C 语言的共享内存代码片段

python 删除数组中的空对象

c++ - Qt,内存的动态分配

每 3 秒调用一次函数

java - java中二维数组的顺序打乱

javascript - 如何从数组中删除具有相同值的项目