简体   繁体   中英

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?

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. That only works for static arrays .

Also, you are redeclaring chant which is simply an error.

In conclusion, since you do not know the number of elements in chant , there is no way to do what you want to do.

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).

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM