Please, tell me, what is the correct way of copying allocated char array to “normal” char array?
I have attempted to do the following, but it fails :
char * buf = (char *) malloc (BUFSIZ * sizeof(char));
// filling up the allocated array with stuff...
char temp[BUFSIZ];
strcpy(temp, buf); // strcpy doesn't work
First things first, you should not cast the return value of
malloc(in C anyway) since it can hide errors.Secondly, you never need to multiply by
sizeof(char)since it’s always guaranteed to be one – doing so clogs up your code.And, as to the actual question, you can use:
to copy the entire character array.
I’m assuming that’s what you want because you make no mention of handling C “strings”, only a character array.
If indeed you are handling C strings,
strcpywill work fine in this case, provided:For example, this little snippet works fine: