sty2_lol
sty2_lol

Reputation: 1

assignment from char * to a void *

working on a hacker-rank problem, the Printing tokens in C. My question does not come from the logic of the problem. i.e. finding the space and instead printing a '\n' rather it comes from the bit of code that is given.

char *s;
s = malloc(1024 * sizeof(char));
scanf("%[^\n]", s);
s = realloc(s, strlen(s) + 1);

Im compiling on a Mac terminal window and am getting an incompatible type from char * to void * Ive tried a few things including type casting, but that seems to get me deeper into trouble. Can someone explain what else my issue is? Thanks

Upvotes: 0

Views: 763

Answers (1)

DarenW
DarenW

Reputation: 16906

If you are compiling this as C++, then the void* return value from malloc (which is rarely used in C++) and realloc must be cast to char*. C++ has stricter rules about these things. The proper way is to use one of the newer templated cast operators, such as reinterpret_cast<char*>. But a simple (char*) should still work fine:

s = (char*)malloc(...)

Since the code looks like plain old C, the sort of code that might have been written in the 1980s, the best thing is to name the source file something.c (not something.cpp or something.cxx etc.) The compiler will then use the more lenient rules of C, putting out some warnings but probably not an error. Though beware, C has had newer versions defined, none of which I've kept up with, and compilers have been growing new types of error and warning detection, include techniques of static analysis, that might report an error anyway.

Upvotes: 1

Related Questions