简体   繁体   English

函数中的malloc数组如何在函数中

[英]How malloc array in struct in function

I have struct: 我有结构:

typedef struct akcie
{
    int *stockArray;
} AKCIE;

Declaration 宣言

 AKCIE *idStock;

Malloc 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; 现在我想将malloc分配给每个idStock [i],i = 1,2,3,.....函数中的stockArray等。void(parameters){malloc每个idStock [i] .stockArray; }. }。

How to alloc idStock[0], idStock[1] in function? 如何在函数中分配idStock [0],idStock [1]? I dont know how to transmit the struct as parameter. 我不知道如何传递结构作为参数。 Thank you for help. 谢谢你的帮助。

Two malloc s are required. 需要两个malloc One for the AKCIE array and another for each int array. 一个用于AKCIE数组,另一个用于每个int数组。 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. 假设将idStock视为一个数组,并且id是该数组的长度,则您未分配适当的空间量。 You're only allocating space for a number of int variables, but the struct contains an int * , which may not be the same size. 您只为多个int变量分配空间,但是结构包含int * ,其大小可能不同。

What you want is this: 您想要的是:

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

This allocates an array of AKCIE s of length id . 这将分配一个长度为idAKCIE数组。 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. PS:idStock的内存分配有误。 It does not contains int , but int * . 它不包含int ,但包含int *

To avoid this kind of mistakes you can just pass the whole structure to the function sizeof() . 为了避免这种错误,您可以将整个结构传递给函数sizeof()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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