将字节复制到字节数组?

时间:2012-12-23 00:41:50

标签: c++

我正在学习,我想知道如何进行以下数组复制的最佳方法,请考虑以下代码:

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[]的末尾,然后将字节0x000x4E附加到结束了吗?

有人能提供解决方案吗? 非常赞赏。

2 个答案:

答案 0 :(得分:0)

您正在使用动态数组,因此sizeof(chant)将始终是指针的大小,而sizeof(chant) / sizeof(chant[0])将不是数组中元素的数量。这仅适用于静态数组

此外,您正在重新声明chant,这只是一个错误。

总之,由于您不知道chant中的元素数量,因此无法做您想做的事情。

答案 1 :(得分:0)

根据我的理解,在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