Basic C question on copying char arrays to char pointers

cchar

I have some doubts in basic C programming.

I have a char array and I have to copy it to a char pointer. So I did the following:

char a[] = {0x3f, 0x4d};
char *p = a;     
printf("a = %s\n",a);
printf("p = %s\n",p);
unsigned char str[] = {0x3b, 0x4b};
unsigned char *pstr =str;
memcpy(pstr, str, sizeof str);
printf("str = %s\n",str);
printf("pstr = %s\n",pstr);

My printf statements for pstr and str get appended with the data "a".
If I remove memcpy I get junk. Can some C Guru enlighten me?

Best Answer

Firstly, C strings (the %s in printf) are expected to be NUL-terminated. You're missing the terminators. Try char a[] = {0x3f, 0x4d, 0} (same goes for str).

Secondly, pstr and str point to the same memory, so your memcpy is a no-op. This is a minor point compared to the first one.