-1

I have a struct like this:

typedef struct {
    int hi;
} my_struct;

Is there an advantage in using this:

my_struct *test = malloc(sizeof(my_struct));
test->hi = 1;

Instead of this:

my_struct test;
test.hi = 1;
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
tejas
  • 159
  • 2
  • 13
  • 3
    It depends on what you are doing. Just seeing those two snippets of code, there is no practical difference (except in the first case where you allocate dynamically you must not forget to `free` the memory). – Some programmer dude Aug 30 '16 at 16:15
  • 1
    Both would allocate memory for your struct, but malloc() will allocate from the heap, `mystruct test` will allocate on the stack – Marc B Aug 30 '16 at 16:16
  • They're useful like when you want your program to actually produce something instead of just have it do private computation unto itself (which a smart compiler would optimize to a no-op). ;-) – Petr Skocik Aug 30 '16 at 16:20

1 Answers1

2

No, usually it's quite the opposite. If you can use the format to satisfy your requrement

my_struct test;
test.hi = 1;

then it's always better, less overhead in runtime. There's no advantage in general of using memory allocator functions, when you can do without them.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261