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.

1
  • That's not how zero-length arrays work. They can only be used with dynamic allocation (as the name "dynamic" suggests). Commented Apr 1, 2013 at 16:39

2 Answers 2

1

You can change invoices to int** invoices and then allocate dynamically using malloc(). You can allocate a 2D array like this:

int** theArray;
theArray = (int**) malloc(arraySizeX*sizeof(int*));
for (int i = 0; i < arraySizeX; i++)
   theArray[i] = (int*) malloc(arraySizeY*sizeof(int));
Sign up to request clarification or add additional context in comments.

5 Comments

This is not an allocation of a 2D array, but of an emulation of such a thing. Also, don't cast the return of malloc, this is not C++.
What would be the real dynamic allocation of a 2D array then?
Please have a look at my answer.
You're doing the same thing except one dimension of the array is fixed to 2.
No, not at all. You are allocating an array of pointers and then a different chunk for each line. Real 2D arrays are allocated contiguously and there is no indirection. The element of a 2D array (something like array[i][j]) can be computed by arithmetic.
1

A pointer to an array with two elements would look like this:

int (*array)[2];

but it would perhaps be easier for you to use a typedef first:

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

and you can allocate a large chunk to such a beast just in on go. If you have a C99 (or upwards) compatible compiler this would read like

array = malloc(sizeof(pair[n]));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.