简体   繁体   中英

casting pointers in C++

I have a serial port returning uint8 in the following way

uint8 bucket[255];
res = COM.com_read((char *)&bucket);

how can i pass bucket pointer into buff pointer in the function given below:

ssize_t send(int s, const void *buf, size_t len, int flags);

& is not required in com_read , and you should write this:

//after removing '&'
//bucket being an array converts to pointer automatically
res = COM.com_read((char *)bucket);  //Dont use &

Or, even a better cast would be static_cast :

res = COM.com_read(static_cast<char*>(bucket)); //C++ Style cast!

And while sending bucket to send , you don't need to cast. It is done implictly by the compiler, because the target type is void* , and any pointer can implicitly convert to void* .

There is no casting required, it is done implicitly (any pointer can be casted to a const void* implicitly).

Note that when explicitly casting, you should prefer C++-casting operators:

res = COM.com_read(static_cast<char *>(bucket));

Static_cast will do the trick to and from void*, but are you sure you need an explicit cast? I think this should be done implicitly for you

static_cast<void *>(bucket)

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