Invalid conversion from void * to char **

Some time has passed since I messed up the C code.

I get the following error when compiling C code under Ubuntu using gcc.

The command I use to compile the code (if these errors are related to the compiler I use, let me know how to do this):

gcc -o runnable mycode.C 

error: invalid conversion from 'void * to' char **

Line 39:

 sequence=malloc(sizeof(char *)*seqNum); 

the sequence is declared as:

 char **sequence; 

seqNum is declared as:

 int seqNum 
+6
c gcc casting malloc
source share
2 answers

Added: Post-solution of the actual Arron problem is provided by sgm in a comment. The text below is accurate and, hopefully, useful, but the second solution to the problem.


Your compiler will write very hard about pointer casts (do you use the C ++ compiler?), Adding an explicit cast like

 sequence=(char**)malloc(sizeof(char *)*seqNum); 

should make a mistake. Alternatively, you can convince the compiler to easily get to you using some option, for example

 $(CC) --lighten-up-baby code.c 

which may be preferable if it is in some third-party code that you really do not want to hack. Read your compiler documentation to find the option you need. Since all gcc at my fingertips (versions 4.0 and 4.2) are happy with this code, I am not in a good place to offer switch tips to disable this behavior.

+7
source share

You need to distinguish the result of malloc from the type you want.

So:

  char ** sequence;
  ...
  sequence = (char **) malloc (sizeof (char *) * seqNum);

Also remember that if you intend to use a sequence, you will need to allocate a list of "char *", as you did, but then you do not have allocated memory, this only allocated space for the list of pointers themselves.

Part of the reason for this is an error in that the assignment between different types of pointers can change the required alignment. Malloc is guaranteed to return a pointer to a space with alignment suitable for any type.

+5
source share

All Articles