user2387537
user2387537

Reputation: 399

Array to array copying using pointers

I'm trying to copy some elements from one array to another and in a way it does work but it copies the whole array when the pointer only points to one element. This is the code:

char buffer[64], buffer1[2];
char* pointer;
strcpy(buffer, "Word");

pointer = buffer1; 
*pointer = buffer[0];
printf("%c\n", *pointer);

printf("%s\n", buffer1);

When I print *pointer to the console I get "W" but when I print buffer1 to the console I get "WÌÌÌÌÌÌÌÌÌWord", how is that even possible? It can only take two elements?

Upvotes: 0

Views: 76

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

how is that even possible? It can only take two elements?

Yeah, and those two elements were printed successfully.

However, since neither of those elements is a '\0', printf had no idea that it had reached the end of your array (how was it to know?!) and kept reading from your computer's memory until it reached a \0 somewhere.

in a way it does work but it copies the whole array when the pointer only points to one element

Pointers only ever "point to one element"; when you use a printf formatter like "%s", which is for a string, the language has to assume that said element has other elements next to it (say, in an array), and it'll keep incrementing the pointer and printing until it finds a '\0' to tell it to stop.

In short, you overran the buffer.

In C, ensure you leave enough room for a terminating NULL byte; in C++, use std::string:

const std::string buffer  = "Word";
const std::string buffer1 = buffer;

std::cout << buffer[0] << '\n' << buffer1 << '\n';

Upvotes: 8

Related Questions