-1

I don't understand why the pointer has to be de-referenced here. char *toParseStr = (char*)malloc(10); Anyone have any ideas?

AkshaiShah
  • 5,739
  • 11
  • 37
  • 45

2 Answers2

6

char *toParseStr = (char*)malloc(10);

There is no dereference here but a cast of the malloc return value to char *. The cast is not required and even should be avoided.

To know why the cast should be avoided:

http://c-faq.com/malloc/mallocnocast.html

ouah
  • 142,963
  • 15
  • 272
  • 331
  • Are there any benefits of casting it? And in what situation would it be useful? – AkshaiShah Nov 19 '12 at 22:00
  • @AkshaiShah It's a style issue, some coders prefer to be explicit in their casts. Also, if you want it to work in C++ as well it requires the cast. – peacemaker Nov 19 '12 at 22:01
  • 2
    @AkshaiShah In c++ the cast is required and I've seen people get into the habit from doing it there; but then using `malloc` in c++ should be a rare event. – dmckee --- ex-moderator kitten Nov 19 '12 at 22:03
  • [Do I cast the result of malloc?](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – iabdalkader Nov 19 '12 at 22:03
  • @mux - The only time you would cast the result of `malloc` is if you are working in C++, or you are using a C compiler that predates the 1989 standard. Prior to C89, `malloc` returned `char *`, not `void *`, so in those days a cast *was* required if the target type was not `char *`. The reason the `void *` type exists is to provide a "generic" object pointer type that can be converted to other object pointer types without needing the cast. – John Bode Nov 19 '12 at 22:15
  • @JohnBode yes I've read the who discussion so I know the pros and cons, that's why I thought that question should be added :) – iabdalkader Nov 20 '12 at 06:53
-2

malloc returns a void*, so the cast is necessary in some cases to prevent compilation errors

Slicedpan
  • 4,995
  • 2
  • 18
  • 33