0

I am trying to put the contents of a char buffer[512] into a word* (type def as data type short). How do I do this? I have tried memcpy but am either getting an exception or it will run but the word* is undefined value after the copy. Any advice would be appreciated. Thanks.

4
Contributors
5
Replies
6
Views
9 Years
Discussion Span
Last Post by Ancient Dragon
0

post code, such here is how it might be done

char buffer[512] = "Hello World";
// allocate memory for the new string
char* ptr = new char[strlen(buffer)+1];
// now copy
strcpy(ptr, buffer);
0

What Ancient Dragon said ^^,

But don't forget do delete ptr[]; once you're done with it. Or else you'll get a memoryleak.

0

is there a way to do this same thing, only with a short.

char buffer[512] = "Hello World";
// allocate memory for the new string
word* ptr = new word[strlen(buffer)+1];
// now copy
strcpy(ptr, buffer);

the word is typedef as a short. Force the char[] into a word*?

1

I always hate it when someone changes a descriptive name like short, which is a small integer, to something like word, which to me should be a string of some sort rather than an alias for short. That being said, if you are truly trying to change a string, like a char[] or a char * into a numerical value (of whatever type or typedef you want) then I'd look up stringstreams and maybe sprintf(), strtol(), atoi(), atol(), or atof().

Votes + Comments
yes, its very confusing when people do that.
0

>>is there a way to do this same thing, only with a short.
you mean something like this: where buffer contains the binary bytes of a short integer?

short int X = 123;
char buffer[sizeof(short)];
memcpy(buffer, &x, sizeof(short));
...
...
// now put it back
short int n;
n = *(short *)buffer;
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.