Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this error: incompatible pointer to integer conversion?

Tags:

c

pointers

Please have a look at the code, clang is giving me the error "incompatible pointer to integer conversion", why is it happening?

#include <stdio.h>
#include <stdlib.h>
int main (void)
{
    char* name;
    name = malloc (sizeof(char) * 6);
    *name = "david";
    return 0;
}
like image 343
daNullSet Avatar asked Dec 26 '12 06:12

daNullSet


1 Answers

Whatever is happening is happening at this line:

*name = "david";

The type of *name would be char, as you are dereferencing the char pointed to by name. The type of "david" is char[6], as it's a string literal of 6 chars (5 + null terminator). An array type decays into a pointer and a char is an integral type; your assignment tries to set a pointer to an integer, hence incompatible pointer to integer conversion.

Even if the left side of the assignment had the right type, you couldn't just copy arrays with the assignment operator. If you want to set name to "david", then you should be using strcpy( name, "david" ).

like image 133
K-ballo Avatar answered Oct 04 '22 00:10

K-ballo