简体   繁体   中英

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);

基本上说“将char放置在getSomething指向的位置...”

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM