CString to byte array at specific array index

I need to put a CString into a byte array at a specific index.  I've tried the below method, but it seems to tack on 2 extra bytes of gibberish to the end of the array.

BYTE bArrTemp[18];
CString szWrite;

memset(bArrTemp,0x00,18);

memcpy(&bArrTemp[2],szWrite,szWrite.GetLength());

bArrTemp[0] = TAG_GUID;
bArrTemp[1] = LEN_GUID;

howardsdAsked:
Who is Participating?
 
jkrCommented:
>>I've tried the below method, but it seems to tack on 2 extra bytes of gibberish
>>to the end of the array.

The way you are using that, the NULL terminator for the string might be missing. I'd rather use

#include <tchar.h>

//...

size_t stLen = szWrite.GetLength() * sizeof(TCHAR);

BYTE* bArrTemp = new BYTE[szLen + 1] ;
CString szWrite;

memset(bArrTemp,0x00,szLen + 1);

memcpy(&bArrTemp[2],szWrite,szLen);

bArrTemp[0] = TAG_GUID;
bArrTemp[1] = LEN_GUID;

// delete [] bArrTemp; later when you no longer need it.
0
 
howardsdAuthor Commented:
My mistake, it's actually tacking on a lot of extra bytes of gibberish.
0
 
grg99Commented:
what's the possible length of the  CString?  if it's more than 15, you'll have a problem.

0
 
jkrCommented:
BTW, why aren't you simply using

szWrite[0] = TAG_GUID;
szWrite[1] = LEN_GUID;

instead?
0
 
howardsdAuthor Commented:
It was the damn null terminator I wasn't copying.  Duh.

Thnx!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.