简体   繁体   中英

Assign string uint8_t

I am struggling to use a uint8_t* to point the first field of a string.

This is how my code looks like

std::string data1
uint8_t* data

data = (uint8_t*)data1[0]

What is wrong here? When I run it it crashed

Thanks in advance

data[0] returns a reference to the first char in the string (provided the string is not empty, otherwise the return value is undefined). You are type-casting the value of that char to a pointer. So, your code crashes when it tries to use the pointer to access an invalid memory address. You need to type-cast the address of that char instead:

data = (uint8_t*) &data1[0];

Or, in a more C++-ish (and safer) manner:

data = reinterpret_cast<uint8_t*>(&data1[0]);

Or, with bounds checking:

data = reinterpret_cast<uint8_t*>(&(data1.at(0)));

For what you want to do you could try:

data = (uint8_t*)data1.c_str();

Don't know exactly what are you trying to achieve, but there is for sure a better approach.

For example if you are doing something like :

std::string data1 = "One"

then data1[0] gives 'O' whose ASCII value is 79. Now you use this 79 as an address.

So, the pointer named data has value 79 in it.

So when you use this pointer in your code again, you are actually attempting to read or write protected memory(0x0000004F or 79). Hence, its crashes at run time.

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