字符数组复制到另一个字符数组 [英] Copy char array to another char array
问题描述
我想没有成功到字符数组复制到另一个。我曾尝试复制的memcpy的direcly地址从一个到另一个,是这样的:
无效包括:(INT ID,焦炭名[16]){
INT I; 对于(i = 0; I< SZ;我++){
如果(A [I] .ID == 0){
一个[I] .ID = ID;
的memcpy(安培;一个[I] .name和&安培;名称,strlen的(名字)+1);
返回;
}
}
}
但显然只有在这个函数的作品。我曾尝试也是这样: http://www.cplusplus.com/reference/clibrary / CString的/的memcpy / ,但没有奏效。
有人可以帮我吗?
下拉的&安培;
从&放大器;名称
,它应该工作。你的函数声明产生误导;它实际上等同于:
无效包括:(INT ID,字符*姓名)
编译pretends该阵列
参数被声明为指针
块引用>如果
。名称
将是一个数组,名称==&放大器;名称
。但名称
为指针,以便名称=安培;!名字
的C常见问题有一些问题,可以帮助:
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?
解决方案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
. Butname
is a pointer soname != &name
.The C FAQ has some questions that might help:
这篇关于字符数组复制到另一个字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!