Click here to Skip to main content
16,017,788 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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));
}
Posted
Updated 14-May-17 21:13pm
v2

Try

C++
c_array = (Activity *)calloc( num_challenges, sizeof(Activity) );
 
Share this answer
 
Comments
Rick York 14-May-17 21:00pm    
calloc is just malloc with two differences : it takes two parameters, a size and a count; and it zeroes the allocated memory.
kasandra77 14-May-17 21:11pm    
i tried this like you saied :
((*sys)->c_array) = (Activity *)calloc( num_challenges, sizeof(Activity) );
i think it worked ! i can't check it for sure today(i need to sleep) but tomorrow i am gonna test it !
thank you a lot
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;
}
 
Share this answer
 
Comments
kasandra77 15-May-17 4:41am    
oh thank you so much !! one question: if i kept the activity* i wouldn't be able to do free to the memoty outside of this function ?
Jochen Arndt 15-May-17 4:56am    
If you keep the Acticity* you would have a local variable and the passed structure would not be changed.

But you might use this instead:
Activity *temp = malloc(num_challenges * sizeof(Activity));
*sys->c_array = temp;
kasandra77 15-May-17 14:21pm    
ok thank you so much !!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900