Reputation: 633
I would like to try C memcpy function. I have this code:
char destination[40];
memcpy(destination, "My favorite destination is...", 11);
printf(destination);
I woul like to copy first 11 letters to destination array. When I use printf, the result is "My favorite2". Why?
Upvotes: 3
Views: 4843
Reputation: 23868
C strings must be null terminated. Simplest solution is to copy 0's into the whole string first.
memset(destination, 0, sizeof(destination));
Upvotes: 3
Reputation: 3951
That is because memcpy
does not terminate the string with a null byte. You could start by filling the entire array with nulls:
memset(destination, 0, sizeof destination);
Upvotes: 3
Reputation:
You are missing the NULL terminator at the end of the 11 characters -> Printf is just printing whatever is in that part of memory until it finds a NULL terminator.
Simply add in destination[11] = 0;
That should work :)
Upvotes: 10