0

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?

6
  • You haven't null terminated buffer1 Commented Jun 6, 2014 at 18:21
  • @LightnessRacesinOrbit sorry I must have clicked "C" as a suggestion Commented Jun 6, 2014 at 18:22
  • 2
    Right well this is not how one writes C++! :) Commented Jun 6, 2014 at 18:22
  • @Praetorian Thank you it works now but could I ask why does not null terminating buffer1 give me "WÌÌÌÌÌÌÌÌÌWord"? Commented Jun 6, 2014 at 18:25
  • 1
    @user2387537 Nothing that it prints after the first W is guaranteed. It's just whatever happens to be in those memory locations. Lightness' answer provides a good explanation of what's going on. Commented Jun 6, 2014 at 18:29

1 Answer 1

8

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';
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.