nSack
nSack

Reputation: 65

Can you create an array of Structure inside of another structure in C language?

Aim : To create a structure of element having certain properties. Then utilize that structure type by creating it's array in another structure.

struct Element
{
    int i;
    int j;
    int x;
};

struct Sparse
{
    int r;
    int c;
    int n;
    struct Element *ele;
    ele = (struct Element *)malloc(n*sizeof(struct Element));    
}; 

What I wish to know is that which part of the code am I not allowed to write while creating a structure.

Upvotes: 0

Views: 599

Answers (3)

abelenky
abelenky

Reputation: 64682

The common way to do this is:

struct Element
{
    int i;
    int j;
    int x;
};

struct Sparse
{
    int r;
    int c;
    int n;
    struct Element ele[0];  // Make a zero length array
}; 

struct Sparse* MakeNewSparse(size_t num_ele)
{
    struct Sparse* sparse = malloc(sizeof(*sparse) + num_ele*sizeof(struct Element));
    return sparse;
}

This works because accessing off the end of a zero-length array is totally legal in C, provided you have allocated memory there.

In this example, we allocate enough space for the struct Sparse, and then enough more contiguous space for the array of struct Element.

After that, accessing element sparse->ele[5] is totally legal.

Upvotes: 1

John Bode
John Bode

Reputation: 123458

The line

ele = (struct Element *)malloc(n*sizeof(struct Element));   

should not be part of the struct definition - that's something you do at runtime, along these lines:

struct Sparse s; // create new struct Sparse instance

s.n = get_some_size();
s.ele = malloc( s.n * sizeof *s.ele );  // no need for cast

Upvotes: 1

kjh6b6a68
kjh6b6a68

Reputation: 509

struct in c is syntactically similar with types like int, char, etc. The definition of a struct is for compiler to know how to use variable declared with that struct such as struct Sparse var;. So the definition of a struct is not actually the code itself. It will be used at compile time.

However, malloc() is a function, which will be used at runtime, so it is nonsense to put malloc() in your struct definition.

Upvotes: 0

Related Questions