开发者

Casting a pointer from a char in C

If I have a function that returns a (char) in c and I have a (char* getSomething) how do I cast it? It is giving me an error when I try to cast it through either (char*) or (开发者_高级运维char*)&

Example: If the function is :

char* getSomething;
getSomething = getSth(var);

getSth return a char


You cannot store a value in a pointer. A pointer points to a memory address where data is stored, so you must first store the returned character to a memory location (a character variable or malloc'ed region) which can then be pointed to by getSomething.

char *getSomething;
char something;

something = getSth(var);
getSomething = &something;

Or you can directly access the memory location with the pointer

char something;
char *getSomething = &something;

*getSomething = getSth(var);

Finally, you could use malloc to return a region of memory to point at and then store the returned value in this memory location. Just make sure that you free this memory before the function exits.

char *getSomething = malloc(sizeof(char));

*getSomething = getSth(var);

free(getSomething);


*getSomething = getSth(var);

Basically it says "put the char where getSomething points to..."

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜