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
inprintf
) are expected to be NUL-terminated. You're missing the terminators. Trychar a[] = {0x3f, 0x4d, 0}
(same goes forstr
).Secondly,
pstr
andstr
point to the same memory, so yourmemcpy
is a no-op. This is a minor point compared to the first one.