简体   繁体   English

在C中返回二维数组

[英]Returning a 2-dimensional array in C

This is dumb, but I'm having trouble getting the right type signature or something. 这是愚蠢的,但我无法获得正确的类型签名或其他东西。 I want to have a function return a two-dimensional array (fixed size on one dimension, variable on the other) but I'm doing something wrong. 我想让一个函数返回一个二维数组(一个维度的固定大小,另一个维度的变量)但我做错了。 Minimal example: 最小的例子:

void useit(unsigned long sz) {
    uint32_t arr[sz][8] = makeit(sz);
    // Do something useful with arr here
}

// Stub function for allocating and filling an array
uint32_t (*makeit(ulong sz))[8] {
    uint32_t (*arr)[8] = malloc(8*sz*sizeof(int));
    int i, j;
    for (i = 0; i < sz; i++) {
        for (j = 0; j < 8; j++) {
            arr[i][j] = 10*i+j+11;
        }
    }
    return arr;
}

But I don't have the signature right, because gcc complains: 但我没有签名权,因为gcc抱怨:

error: incompatible types when assigning to type 'uint32_t[8]' from type 'uint32_t (*)[8]' 错误:从类型'uint32_t(*)[8]'分配类型'uint32_t [8]'时出现不兼容的类型

You cannot use: 你不能使用:

uint32_t arr[sz][8] = makeit(sz);

since VLAs may not be initialized. 因为VLA可能未初始化。

Use: 采用:

uint32_t (*arr)[8] = makeit(sz);

See it working at http://ideone.com/iuqtlJ . 请访问http://ideone.com/iuqtlJ查看。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM