Basic C question on copying char arrays to char pointers
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 开发者_JAVA百科str get appended with the data "a". If I remove memcpy I get junk. Can some C Guru enlighten me?
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.
Add a null terminator, cause that's what you printf expects:
char a[] = {0x3f, 0x4d, '\0'};
The standard way C strings are represented is that in memory, they are a sequence of non-zero bytes representing the characters, followed by a zero (or NULL) byte. You should declare:
char a[] = {0x3f, 0x4d, 0};
When you assign a string pointer (as in unsigned char *pstr = str;
) both pointers point to the same memory area, and thus the same characters. There is no need to copy the characters.
When you do need to copy characters, you should be using strlen()
, the sizeof()
operator returns the number of bytes its argument uses in memory. sizeof(pointer)
is the number of bytes the pointer uses, not the length of the string. You find the length of a string (i.e. the number of bytes it occupies in memory) with the strlen()
function. Also, there are standard functions to copy C strings. You should rely on those to do the right thing:
strcpy(pstr, str);
printf
's %s
expects a 0-terminated string, your strings aren't. The uninitialized memory following your arrays may however happen to start with a 0-byte, in which case your code will appear to be correct - it still isn't.
You're declaring an array "str", then pointing to it with pstr. Note that you have no null-terminating character, so after using memcpy you copy the block to itself with no null terminator, as a string requires. Thus, printf can't find the end of the string and continues printing until it finds a 0 (or '\0' in character terms)
Agreed. You'll have to add a null byte at the end of your array of chars.
char a[] = {0x3f, 0x4d, '\0'};
The reason being is that you're creating a string without declaring where it actually ends. Your memcpy() function copies *str to *pstr and automatically adds a null byte for you, which is why it works.
Without memcpy() there the string never knows when to end, so it reaches into subsequent memory addresses and returns whatever random values are stored there. When you're creating a string out of characters, always remember to end it with a null byte.
精彩评论