views:

106

answers:

4

I get the error assignment makes pointer from integer without a cast on the following code, what does it mean?

char * splitter;
if(splitter = strchr(key, ':') != NULL && *(splitter + 1) == ' ')
+1  A: 

The != operator has a higher precedence than the = operator. That means your expression splitter = strchr(key, ':') != NULL is actually interpreted as splitter = (strchr(key, ':') != NULL).

Put the assignment into parentheses to increase the precedence of that part:

(splitter = strchr(key, ':')) != NULL
Gumbo
+2  A: 

The not-equal operator != has higher precedence than the assignment operator =, so your original line reads like splitter = (strchr(key, ':') != NULL) rather than your intended (splitter = strchr(key, ':)) != NULL, so the compiler tries to assign to splitter the result of the comparison between strchr() and NULL.

Oblomov
+1  A: 

The != has higher precendence than the =. You should fully parenthesize:

if (((splitter = strchr(key, ':')) != NULL) && (*(splitter + 1) == ' '))
Carl Norum
+3  A: 

It is because of the priority of operations. You need to put an extra set of parens to make sure it happens in the right order:

char * splitter;
if((splitter = strchr(key, ':')) != NULL && *(splitter + 1) == ' ')

otherwise the it will evaluate as this:

splitter = (strchr(key, ':') != NULL)

Since strchr(key, ':') != NULL will evaluate to either a 1 or a 0, in your example, you are assigning an integer to a pointer type, hence the warning.

however, i would just write it as in your second example, since it is simpler and less error prone. Making it one line shorter doesn't add anything except complexity.

Evan Teran
I'd write `splitter[1]` instead of `*(splitter + 1)`, too.
Steve Jessop