[英]Copying Bytes to Bytes Array?
I am learning and I'd like to know the best way how to do the following array copy, Consider this code: 我正在学习,我想知道如何进行以下数组复制的最佳方法,请考虑以下代码:
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?
}
how can i put the bytes that are inside of *chant
, and then put them into the end of chant[]
and then append bytes 0x00
and 0x4E
on to the end of it? 我如何才能将
*chant
内的字节放到chant[]
的末尾,然后将字节0x00
和0x4E
附加到它的末尾?
Can anybody provide a solution? 有人可以提供解决方案吗? Much Appreciated.
非常感激。
You are using dynamic arrays so the sizeof(chant)
will always be the size of a pointer, and sizeof(chant) / sizeof(chant[0])
won't be the number of elements in the array. 您正在使用动态数组,因此
sizeof(chant)
始终是指针的大小,而sizeof(chant) / sizeof(chant[0])
不会是数组中元素的数量。 That only works for static arrays . 这仅适用于静态数组 。
Also, you are redeclaring chant
which is simply an error. 另外,您要重新声明
chant
,这只是一个错误。
In conclusion, since you do not know the number of elements in chant
, there is no way to do what you want to do. 总之,由于您不知道
chant
的元素数量,因此无法执行您想做的事情。
According to my understanding, in C++, all arrays passed into a function are treated as pointers no matter they are statically allocated or dynamically allocated or even you write the argument as char chant[]
, (ie, only the address of the first element is passed in). 根据我的理解,在C ++中,传递给函数的所有数组无论是静态分配还是动态分配,甚至您将参数写为
char chant[]
都被视为指针(即,仅第一个元素的地址为通过)。
Example: 例:
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;
}
the result is: 结果是:
size in main: 8
size in f: 1
So as you can see, in f()
, value[]
is the same as value *
, and sizeof(value)
is the size of the pointer. 如您所见,在
f()
, value[]
与value *
相同, sizeof(value)
是指针的大小。
You should (always) also pass in the length when you pass an array into a function. 将数组传递给函数时,还应该(总是)传递长度。
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;
}
The output: 输出:
size in main: 8
size in f: 8
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.