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.

Recommended Answers

All 5 Replies

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);

What Ancient Dragon said ^^,

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

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*?

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().

commented: yes, its very confusing when people do that. +34

>>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;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.