0

I'm trying without success to copy a char array to another one. I have tried memcpy copying direcly the address from one to another, like this:

void include(int id, char name[16]) {
int i;

  for (i = 0; i < SZ; i++) {
      if (a[i].id == 0) {
          a[i].id = id;
          memcpy(&a[i].name, &name, strlen(name)+1);
          return;
      }
  }
}

But obviously works only inside of this function. I have tried also like this: http://www.cplusplus.com/reference/clibrary/cstring/memcpy/ but it didn't work. Can someone help me?

4
  • 1
    What is a? You should change it to: memcpy(&a[i].name, name, strlen(name)+1); because name is an array, and an array's name is already a pointer to the first element. Commented Jun 24, 2011 at 21:11
  • 1
    Why can't you use strcpy if the char arrays are null terminated? Commented Jun 24, 2011 at 21:11
  • 3
    Can you include a as an argument to the function include? Rather than having it as a global variable ... Commented Jun 24, 2011 at 21:17
  • @GWW - I prefer memcpy as it gives you the chance to protect against overrun in both buffers. Though ghe OP isn't exactly doing that... Commented Jun 24, 2011 at 21:30

1 Answer 1

4

Drop the & from &name and it should work. Your function declaration is misleading; it's actually equivalent to:

void include(int id, char *name)

The compiler pretends that the array parameter was declared as a pointer

If name would be an array, name == &name. But name is a pointer so name != &name.

The C FAQ has some questions that might help:

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer, but it only works if the first parameter of memcpy is a char. In my case the variable a is a struct with a char name[16] inside. And when I debug passing memcpy(&a[i].name, name, strlen(name)+1) the compiler give me an address out of bounds.
Thanks @cnicutar, you were right since the beginning! I changed all things like you said but forgot to change the struct declaration. Now it works! Thank you! :)

Your Answer

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