我该如何让它发挥作用?我不确定客户将被分配多少张发票,并且希望使其保持动态。请帮忙。
#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/