Trouble with memcopy

Hey guys,

I'm having trouble understanding this...

char* buffer = "My name is steve.";
char* name = new char[5];
memcpy(name, &buffer[11], 5);
cout << name;

Why doesn't it return "steve"? Instead I get something like "steve²²²²½½½½½½½½■ε■ε■ε■" telling me that there is something wrong with the range, yet its correct. What am I doing wrong or not considering?

Thanks!
C-style strings have a null terminating character ( 0, or '\0' ) to indicate that you've reached the end of the string. Therefore you would need to put this null terminator at the end of the string (and thus, you'd need to allocate an extra byte:

1
2
3
4
5
6
7
8
9
10
const char* buffer = "My name is steve.";
char* name = new char[5+1];  // +1 for the null terminator
memcpy(name, &buffer[11], 5);
name[5] = 0;  // put in the null terminator at the end
cout << name;  // now it prints "steve" as expected

// for fun and experimenting, put the null somewhere else:

name[2] = 0;
cout << name;  // now it only prints "st" 
Last edited on
Ahhhh! Now i follow, thanks so much!
Topic archived. No new replies allowed.