// the malloc style, which returns a pointer:
struct Cat *newCat = malloc(sizeof(struct Cat));
// no malloc...but isn't it actually the same thing? uses memory as well, or not?
struct Cat cat = {520.0f, 680.0f, NULL};
Basically, I can get a initialized structure in these two ways. My guess is: It’s the same thing, but when I use malloc I also have to free() that. In the second case I don’t have to think about memory, because I don’t call malloc. Maybe.
When should I use the malloc style, and when the other?
Firstly, the first variant does not initialize any structure. It simply allocates a block of raw memory sufficient to hold an object of
struct Cattype. The memory remains uninitialized (contains garbage). The second variant does initialize each field in the structure to a specific value.Secondly, the first variant creates a nameless [and uninitialized]
struct Catobject with allocated storage duration. The object will live until you explicitly deallocate it withfree(or until the program ends). The second variant creates a named objectcatwith automatic storage duration – it will be deallocated automatically at the end of its declarative region (at the end of the containing block).Thirdly, in practice the two variants create objects in different kinds of memory. The first variant creates the object in the heap, while the second variant will typically create it on the stack.
As for when to use one or another, there are quite a few answers here on SO to that question. This thread has some answers and plenty of links.