What are the differences between these two declarations for a struct?
Btw, I wrote this code; this is not homework or anything. And apologies, but the code below is written in C.
typedefstruct structA{
int x;
int *y;
} A;
void init (A *param){
int *ptr;
param->x = 5;
param->y = ptr;
}
int main(){
A var1;
A *var2;
//We malloc var2...
var2 = (A*)malloc(sizeof(A));
//Now this is what I need help with...
init (&var1);
init (var2);
printf("%d\n", var1.x);
printf("%d\n", var2->x);
return 0;
}
var1 is stored in stack space and var2 is stored in heap space. Are there any direct differences between these two declarations?
The question I really would like to ask is: what is the benefit of having a pointer to a struct when I could do the exact same operations as with simply declaring a type struct variable stored in stack space?
Both var1 and var2 is stored on the stack. var2 points to an object on the heap.
Allocating objects on the heap is useful when you don't want the object to be destroyed when the current scope ends. The stack space is also much more limited so if you are creating lots of objects and/or large objects it's sometimes necessary to use the heap.
Prefer the stack (because the code is cleaner) and use the heap only when necessary (because it complicates things and it's easy to forget freeing the object).