[英]Copying Bytes to Bytes Array?
我正在学习,我想知道如何进行以下数组复制的最佳方法,请考虑以下代码:
void Cast1LineSpell(UINT Serial, char *chant)
{
byte packet[] = { 0x0F, 0x03,
(Serial >> 24) & 0xFF, (Serial >> 16) & 0xFF,(Serial >> 8) & 0xFF, Serial & 0xFF,
0x9A, 0x92, 0x00, 0x00, 0x00, 0x1A };
byte prepareSpell[2] = { 0x4D, 0x01 };
byte chant_length = sizeof(chant) / sizeof(chant[0]);
byte chant_name[] = { 0x4E, chant_length, }; // <= how can i put the bytes in chant* into the rest of this array, and then append bytes 0x00 and 0x4E on to the end of it?
}
我如何才能将*chant
内的字节放到chant[]
的末尾,然后将字节0x00
和0x4E
附加到它的末尾?
有人可以提供解决方案吗? 非常感激。
您正在使用动态数组,因此sizeof(chant)
始终是指针的大小,而sizeof(chant) / sizeof(chant[0])
不会是数组中元素的数量。 这仅适用于静态数组 。
另外,您要重新声明chant
,这只是一个错误。
总之,由于您不知道chant
的元素数量,因此无法执行您想做的事情。
根据我的理解,在C ++中,传递给函数的所有数组无论是静态分配还是动态分配,甚至您将参数写为char chant[]
都被视为指针(即,仅第一个元素的地址为通过)。
例:
void f(int value[]){
cout<<"size in f: "<<sizeof(value)/sizeof(int)<<endl;
}
int main(){
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
cout<<"size in main: "<<sizeof(arr)/sizeof(int)<<endl;
f(arr);
return 0;
}
结果是:
size in main: 8
size in f: 1
如您所见,在f()
, value[]
与value *
相同, sizeof(value)
是指针的大小。
将数组传递给函数时,还应该(总是)传递长度。
void f(int value[], size_t size){
cout<<"size in f: "<<size<<endl;
}
int main(){
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
size_t size = sizeof(arr)/sizeof(int);
cout<<"size in main: "<<size<<endl;
f(arr, size);
return 0;
}
输出:
size in main: 8
size in f: 8
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.