-1

Guys I'm programing in C, trying to do a dynamic allocation of a type char like this :

char **word1 = malloc(sizeof(char *)* 1);
char **word2 = malloc(sizeof(char *) * 1);

But it is resulting an erro like that: invalid conversion from 'void*' to 'char**' [-fpermissive]

Thanks every one who help me.

  • malloc returns `void*` you need to cast to `char*` put a `(char*)` after the equals sign. – Tim Seguine Dec 04 '14 at 09:19
  • 2
    Then you're most likely not compiling C code, but C++ code. And if you're programming C++ then you should not use `malloc`/`free`, in fact these days you barely have to use pointers at all in C++. – Some programmer dude Dec 04 '14 at 09:20
  • looks like error from a C++ compiler to me. – sgarizvi Dec 04 '14 at 09:20
  • 8
    @TimSeguine Please [don't](http://stackoverflow.com/a/605858/3194340) – n0p Dec 04 '14 at 09:20
  • @Coconop I personally prefer to try to stay in the intersection of C and C++ when I am writing in C. That is a tradeoff which your link doesn't consider, and it is a reasonable one to make. In that case you have to adhere to the stricter type rules, which isn't a bad thing. – Tim Seguine Dec 04 '14 at 09:30
  • @Tim Seguine Buhhhhh Never cast malloc()'s return value in C. OP is probably using C++ and doesn't even know. Or is running on MSVC and doesn't know how to setup to C correctly. But don't tell some one who says he is working in C he has to cast the return value of `malloc()` – dhein Dec 04 '14 at 09:35
  • @TimSeguine The problem of the intersection is: You are lead to use itnersections, where are no itnersections. Most intersections, some one is using aren't covered by neither C nor C++ standard. And it leads bad styled code. Better decide before when to sue plain C and when C++ would be better. And get the straight differences ;) – dhein Dec 04 '14 at 09:38
  • @Zaibis If someone is confused by the difference between C and C++ then I can admit that it might not be the best advice. But the best argument against casting(forgetting stdlib.h) in this case doesn't apply as long as your warning level is high enough(which it should be anyway). The other arguments are stylistic and thus subjective. – Tim Seguine Dec 04 '14 at 09:51

2 Answers2

7

An educated guess: you're using a C++ compiler. C doesn't need any casts from void* to other pointer types, but C++ does.

Consider either using a C compiler, or casting the value returned by malloc.

Frerich Raabe
  • 90,689
  • 19
  • 115
  • 207
6

In c compiler [gcc], this error would not show up.

In c++ compiler, [g++], this error is likely to happen.

To get rid of this,either

  1. Use a c compiler to compile the above code.
  2. Use a c++ compiler and add a char ** cast to malloc() return value.

Note: IMO, go for the 1st point. It's not a good practice neither to use malloc() family in c++, nor casting the return of malloc().

Community
  • 1
  • 1
Natasha Dutta
  • 3,242
  • 21
  • 23