struct element {
int val;
int z;
};
typedef struct element ELEM;
Look at this example:
int main()
{
ELEM z;
z =
In your first example,
int main() {
ELEM z;
z = 6;
printf("%d",z);
}
You are creating a z
Elem
on the stack. This is a very efficient operation, and the language will manage the memory allocated to z
for you - that is when z
goes out of scope it will automatically be freed. In contrast, your second example,
ELEM *z;
Creates a pointer on the stack (which is a 32-bit value on a 32-bit OS, and a 64-bit value on a 64-bit OS) but does not allocate any elements. That is the purpose of the malloc
routine, to allocate memory on the heap. You may point to one (as in your example), or many different elements dynamically through your pointer into the heap and you must free memory you allocate.