开发者

Copy char array to another char array

开发者 https://www.devze.com 2023-03-15 02:09 出处:网络
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:

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.cp开发者_运维技巧lusplus.com/reference/clibrary/cstring/memcpy/ but it didn't work. Can someone help me?


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:

  • Array parameters
  • Array parameter size
0

精彩评论

暂无评论...
验证码 换一张
取 消