copying part of the char array to a string in c
I have read many suggested questions, but still cannot find out the answer. I know the content in buffer is a NULL terminated char array
, and I want to copy it into a dynamic allocated char array
. However, I kept getting segmentation fault from the strcpy
function. Thanks for any help.
void myFunction()
{
char buffer[200];
// buffer was filled by recvfrom correctly, and can be printed out with printf()
char *message = malloc(200);
strcpy(message, buffer[1]);
}
////////////////
ok, so i tried strcpy(message, &buffer[1]); strcpy(message, buffer);
but not开发者_JAVA技巧hing worked!!
This works for me. Is it possible that your buffer is not null-terminated?
char buffer[200];
buffer[0] = 'h';
buffer[1] = 'e';
buffer[2] = 'l';
buffer[3] = 'l';
buffer[4] = 'o';
buffer[5] = '\0';
// buffer was filled by recvfrom correctly, and can be printed out with printf()
char *message = (char *)malloc(200);
strcpy(message, buffer);
Your invocation of strcpy(3)
is incorrect. Change it to the following:
buffer[199] = '\0';
strcpy(message, &buffer[1]);
strcpy(3)
has the following signature:
char *
stpcpy(char *s1, const char *s2);
You passed in:
char *stpcpy(char *s1, const char s2); /* won't work */
I would suggest using memcpy(3)
instead of strcpy(3)
since strcpy(3)
relies on a null character to terminate the string.
精彩评论