简体   繁体   English

分配字符串uint8_t

[英]Assign string uint8_t

I am struggling to use a uint8_t* to point the first field of a string. 我正在努力使用uint8_t*指向字符串的第一个字段。

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). data[0]返回对字符串中第一个char的引用(假设字符串不为空,否则返回值未定义)。 You are type-casting the value of that char to a pointer. 您正在将该char类型转换为指针。 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: 您需要改型输入该char地址

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

Or, in a more C++-ish (and safer) manner: 或者,以一种更加C ++风格(更安全)的方式:

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. 然后data1 [0]给出ASCII值为79的'O'。现在您将此79用作地址。

So, the pointer named data has value 79 in it. 因此,名为data的指针中具有值79。

So when you use this pointer in your code again, you are actually attempting to read or write protected memory(0x0000004F or 79). 因此,当您再次在代码中使用此指针时,实际上是在尝试读取或写入受保护的内存(0x0000004F或79)。 Hence, its crashes at run time. 因此,它在运行时崩溃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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