c - typedef 中的动态二维数组

标签 c arrays

我该如何让它发挥作用?我不确定客户将被分配多少张发票,并且希望使其保持动态。请帮忙。

#include <stdio.h>
#include <stdlib.h>

typedef struct _cust{
    int id;
    int invoices[][2];
} cust;

cust account[] = {
    {1,{10,100}},
    {2,{{10,100},{20,200}}},
    {3,{{10,100},{20,200},{30,300}}}
};

int main(void) {
    printf("%d\n", account[0].invoices[0][0]);
    printf("%d\n", account[1].invoices[1][0]);
    printf("%d\n", account[2].invoices[2][0]);
    return 0;
    }

当我运行此代码时,出现以下错误...

error: initialization of flexible array member in a nested context

如果我填写一个类似 int Invoices[3][2] 的数字,代码运行正常。

最佳答案

您可以将发票更改为int**发票,然后使用malloc()动态分配。 您可以像这样分配一个二维数组:

int** theArray;
theArray = (int**) malloc(arraySizeX*sizeof(int*));
for (int i = 0; i < arraySizeX; i++)
   theArray[i] = (int*) malloc(arraySizeY*sizeof(int));

关于c - typedef 中的动态二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15747375/

相关文章:

javascript - 循环响应对象并使用 javascript/jquery 显示 id 和名称

c - 将单词列表扫描到数组中的槽中

python - 如何将元组转换为 numpy 数组?

ruby - 有没有更好的方法来查找数组中最小元素的位置?

c - time_t 是什么原始数据类型?

c - 用 '%20' 替换字符串中的所有空格。假设字符串在字符串末尾有足够的空间来容纳额外的字符

c - 如何处理多线程进程的 fork 错误?

c - Lua liblua5.1.so 无法打开共享对象文件

编译所有 C 文件并使用 Makefile 创建可执行文件

javascript:构建数组项的条件