简体   繁体   中英

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.

Two malloc s 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));

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 AKCIE s of length id . Once you do this, you don't need to allocate the individual array members, since it's already done.

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM