Schrami
Schrami

Reputation: 89

How malloc array in struct in function

I have struct:

typedef struct akcie
{
    int *stockArray;
} AKCIE;

Declaration

 AKCIE *idStock;

Malloc idStock

idStock = ( AKCIE *)malloc( id * sizeof( int )); // id is an integer

Now I want to malloc to every idStock[i], i = 1,2,3,..... stockArray in function, etc. void(parameters) { malloc every idStock[i].stockArray; }.

How to alloc idStock[0], idStock[1] in function? I dont know how to transmit the struct as parameter. Thank you for help.

Upvotes: 0

Views: 128

Answers (3)

Fiddling Bits
Fiddling Bits

Reputation: 8861

Two mallocs are required. One for the AKCIE array and another for each int array. Below is an example for statically sized arrays:

#define STRUCT_ARRAY_DEPTH (10)
#define INT_ARRAY_DEPTH    (20)

int i;
AKCIE *idStock;

idStock = malloc(STRUCT_ARRAY_DEPTH * sizeof(*idStock));
for(i = 0; i < STRUCT_ARRAY_DEPTH; i++)
    idStock[i].stockArray = malloc(INT_ARRAY_DEPTH * sizeof(int));

Upvotes: 1

user5609732
user5609732

Reputation:

This is how you can alloc the memory for each of the elements in the struct.

This is the procedure:

void procedure(AKCIE *idStock, int n){ //n is the dim
        int i;
        for(i=0; i<n; i++){
          idStock[i].stockArray = (int *)malloc(HOW_MANY_DO_YOU_NEED * sizeof(int));
        }
    }

and this is how you call it:

    .
    .
    .
    procedure(idStock, dim);
    .
    .
    .

PS: there is an error in your allocation of memory for idStock. It does not contains int, but int *.

To avoid this kind of mistakes you can just pass the whole structure to the function sizeof().

Upvotes: 0

dbush
dbush

Reputation: 224157

This is incorrect:

idStock = ( AKCIE *)malloc( id * sizeof( int ));

Assuming idStock is to be treated as an array, and id is the length of that array, you're not allocating the proper amount of space. You're only allocating space for a number of int variables, but the struct contains an int *, which may not be the same size.

What you want is this:

idStock = ( AKCIE *)malloc( id * sizeof( AKCIE ));

This allocates an array of AKCIEs of length id. Once you do this, you don't need to allocate the individual array members, since it's already done.

Upvotes: 0

Related Questions