如何为函数中的结构分配内存? [英] How to allocate memory to a struct in a function ?

查看:69
本文介绍了如何为函数中的结构分配内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这个函数中有一个函数create_system我想将内存分配给一个名为c_array的数组,它的tipe是一个指向struct Activity的指针。

i得到我尝试分配的方式记忆错了!我尝试了所有的东西,我搜索了整个谷歌以这种方式分配:

活动*((* sys) - > c_array)= malloc(num_challenges * sizeof(活动)); 



但我得到了以下错误:

预期')'之前' - >'令牌



我在这里做错了任何帮助!提前谢谢



我尝试过:



 typedef struct SRoomSystem 
{
Activity * c_array;

} RoomSystem;
int num_challenges = 6; //这只是一个例子
结果create_system(RoomSystem ** sys){
活动*((* sys) - > c_array)= malloc(num_challenges *的sizeof(活动));
}

解决方案

尝试



 c_array =(活动*)calloc(num_challenges, sizeof (活动)); 


< blockquote>内存分配调用正确但分配错误。通过以类型 Activity * 开始行,您告诉编译器创建一个在类型后指定名称的局部变量。但是该名称无效,因为它包含不允许的字符,您可能不想创建局部变量,而是将已分配的内存分配给传递的结构。



如果你拥有现有 RoomSystem 结构的地址 * sys

 sys-> c_array = malloc(num_challenges * sizeof(Activity)); 



如果你的函数有 RoomSystem ** sys 参数:

结果create_system(RoomSystem ** sys)
{
* sys-> c_array = malloc(num_challenges *的sizeof(活动));
/ *假设RESULT_ *是结果值* /
return(* sys-> c_array == NULL)? RESULT_NO_MEM:RESULT_OK;
}


i have a function create_system in this function i want to allocate memory to an array called c_array that it's tipe is a pointer to a struct Activity..
i get that the way i tried to allocate the memory is wrong ! i tried everything and i got after searching all over google to this way to allocate :

Activity* ((*sys)->c_array)=malloc(num_challenges * sizeof(Activity));


but i get the follwing mistake :

expected ')' before '->' token


any help of i am doing wrong here ! thank you in advance

What I have tried:

typedef struct SRoomSystem
{
Activity *c_array;

} RoomSystem;
int num_challenges=6;//this is just an example
Result create_system(RoomSystem **sys){
   Activity* ((*sys)->c_array)=malloc(num_challenges * sizeof(Activity));
}

解决方案

Try

c_array = (Activity *)calloc( num_challenges, sizeof(Activity) );


The memory allocation call is correct but the assignment is wrong. By starting the line with the type Activity* you are telling the compiler to create a local variable with the name specified after the type. But that name is invalid because it contains unallowed characters and you probably don't want to create a local variable but assign the allocated memory to the passed structure.

If you have the address *sys of an existing RoomSystem structure:

sys->c_array = malloc(num_challenges * sizeof(Activity));


If you have a function with a RoomSystem **sys parameter:

Result create_system(RoomSystem **sys)
{
    *sys->c_array = malloc(num_challenges * sizeof(Activity));
    /* Assuming RESULT_* are Result values */
    return (*sys->c_array == NULL) ? RESULT_NO_MEM : RESULT_OK;
}


这篇关于如何为函数中的结构分配内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆