0

I am currently working with an embedded system that will be communicating to various devices using serial communication. I use a uint8_t variable for the buffers sent and received by the embedded board. I need to modify these values (preferably using string) and then convert them back to uint8_t after they have been modified. I have created a simple test code for messing around with uint8_t's and strings. The problem I am having is the output from cout only displays "GREE" (regardless of the value of myString, it is always only 4 characters for some reason). I have tried a few ways to accomplish this task and would really appreciate some help. Maybe I'm missing something that's easy to fix? I've been on the computer for almost 8 hours.

string myString = "GREETINGS";
const uint8_t *p = reinterpret_cast<const uint8_t*>(myString.c_str());
myString.assign(p, p + sizeof(p));
cout << myString << endl;

OUTPUT IS: GREE

Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
  • 1
    `p` is a pointer. `sizeof(p)` is going to be the size of a pointer. If your string holds arbitrary bytes, that pointer alone is not going to know how many bytes were held in the string. – Drew Dormann Aug 04 '15 at 22:28
  • I've definitely been looking at the computer too long to miss something like that haha! Thanks Drew, just fixed it. Pays to have fresh eyes take a peak once in a while. – Spencer Voorhees Aug 04 '15 at 22:32
  • [Some say](http://stackoverflow.com/questions/28142011/can-you-assign-a-substring-of-a-stdstring-to-itself) that string self-`.assign` ment is dodgy – M.M Aug 05 '15 at 02:38

3 Answers3

2

regardless of the value of myString, it is always only 4 characters for some reason

Check the value of sizeof(p). Print it using cout. It is the size of a pointer. It is 4 on your platform.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
0

p is the pointer. When you use sizeof() for pointers you will get 4 or 8. It depends on the architecture you use. For x86 - 4, x64 - 8.

myString.assign(p, p + sizeof(p));// assign first 4 symbols to the string

klimov
  • 7
  • 2
-1

As @Drew Dormann points out (pun intended): p is a pointer with size sizeof(p). The size of a pointer is a system specification, which on your system seems to be 4 bytes. A char is 1 byte, so you are seeing 4 chars.

So, we must change the size:

string myString = "GREETINGS";

const uint8_t *p = reinterpret_cast<const uint8_t*>(myString.c_str());

myString.assign(p, p + myString.size());

cout << myString << endl;
The Brofessor
  • 1,008
  • 6
  • 15