0

How do I get this to work? I am not sure how many invoices a customer will be assigned to and want to leave it dynamic. Please help.

#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;
    }

When I run this code I get following error ...

error: initialization of flexible array member in a nested context

If I give fill in a number something like this int invoices[3][2], the code runs fine.

4

2 回答 2

1

指向具有两个元素的数组的指针如下所示:

int (*array)[2];

但您可能更容易使用typedef第一个:

typedef int pair[2];
.
.
pair * array;

你可以为这样的野兽分配一大块。如果您有一个 C99(或更高版本)兼容的编译器,这将类似于

array = malloc(sizeof(pair[n]));
于 2013-04-01T17:01:38.233 回答
1

您可以更改invoicesint** invoices,然后使用动态分配malloc()。您可以像这样分配二维数组:

int** theArray;
theArray = (int**) malloc(arraySizeX*sizeof(int*));
for (int i = 0; i < arraySizeX; i++)
   theArray[i] = (int*) malloc(arraySizeY*sizeof(int));
于 2013-04-01T16:41:55.200 回答