-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; 
3
  • 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). Commented Aug 30, 2016 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 Commented Aug 30, 2016 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). ;-) Commented Aug 30, 2016 at 16:20

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.