user814767
user814767

Reputation:

Copy char array to another char array

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?

Upvotes: 0

Views: 7566

Answers (1)

cnicutar
cnicutar

Reputation: 182639

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:

Upvotes: 4

Related Questions