I'm trying to cast a void*
from a struct member. The struct looks like this:
typedef struct{
int n;
void* string;
}query;
And I want to cast the member string
to char*
and store another string -- lets say str2
--, like this:
char* str2 = "hello";
(*(char*)q.string) = str2;
But it keeps telling me this warning:
example.c: In function 'main': example.c:23:33: warning: assignment makes integer from pointer without a cast [-Wint-conversion] (* (char* )q.string) = str2;
Why is this isn't working?
You don't need a cast, at all.
That said, in your example, query
is a type, not a variable.
Use it like
query q;
q.string = str2;
The warning is correct. Newer versions of gcc have a more helpful message:
warning: assignment to 'char' from 'char *' makes integer from pointer without a cast [-Wint-conversion]
13 | (*(char*)q.string) = str2; | ^
You dereference a char *
which gives you a char
. To that char
type you assign str2
which is of type char *
.
As Sourav Ghosh showed you, you can just do this:
q.string = str2;
If you really want to make the cast explicit:
q.string = (void*)str2;
As you see you were doing the cast on the wrong side.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.