0
struct ArrayQueue *Q = (struct ArrayQueue*)malloc(sizeof(struct ArrayQueue)); 

vs

struct ArrayQueue *Q = malloc(sizeof(struct ArrayQueue));

I am bit confused as to what to use when and exactly what difference do they bear? Intuitively, I feel the first usage is when I'm writing within a function and the second would be when I'm writing within a structure.

Pang
  • 9,564
  • 146
  • 81
  • 122
  • Are you writing in C? – yellowantphil Jul 27 '16 at 17:07
  • Yes I'm writing in C. – Kantshri Baronia Jul 27 '16 at 17:08
  • Both usages have been used by Narsimha Karumanchi in his book... – Kantshri Baronia Jul 27 '16 at 17:09
  • They work the same. See this link: http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – yellowantphil Jul 27 '16 at 17:10
  • I like the second usage (everywhere) because it requires less typing, and there's no need for the cast. You can't write those statements inside a structure anyway, so I'm not sure what you mean in your latest edit. – yellowantphil Jul 27 '16 at 17:13
  • Writing the code from the book as it is: struct ArrayQueue *Queue(int size){ struct ArrayQueue *Q = malloc(sizeof(struct ArrayQueue)); } The link you provided helped, though! :) – Kantshri Baronia Jul 27 '16 at 17:16
  • OK, what you just typed is a function named Queue that returns a pointer to an ArrayQueue struct. It looks like you're declaring a structure at first, but you aren't. Inside the function, you declare a pointer to an ArrayQueue struct, name it Q, and set its value to the output of `malloc`. Anyway, none of this has an effect on whether you cast the output of `malloc`. I don't know why the author is being inconsistent, but you don't need to switch back and forth like that. – yellowantphil Jul 27 '16 at 17:20
  • ok...Thanks a lot @yellowantphil!! – Kantshri Baronia Jul 27 '16 at 17:30

1 Answers1

0

By default the function malloc returns a void*. Although you do not have to explicitly cast to the type you want(the compiler will do that), there are programmers that like to make that clearer.

That`s up to your coding style, both are acceptable.

Michel
  • 133
  • 1
  • 8