Nanik
Nanik

Reputation: 633

memcpy a substring

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

Answers (4)

user411313
user411313

Reputation: 3990

printf("%.11s","My favorite destination is...");

Upvotes: 0

Adrian Cornish
Adrian Cornish

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

drdwilcox
drdwilcox

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

user400055
user400055

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

Related Questions