memcpy(), what should the value of the size parameter be?

前端 未结 12 2188
灰色年华
灰色年华 2020-12-09 09:36

I want to copy an int array to another int array. They use the same define for length so they\'ll always be of the same length.

What are the pros/cons of the followi

12条回答
  •  情书的邮戳
    2020-12-09 09:55

    sizeof(X) always gives you the NUMBER OF BYTES of "X" if X is a uint16_t array of 10, then sizeof(X) will return 20

    uint16_t X[10]={0};
    cout<<"sizeof x: "< sizeof x: 20
    

    if you want the number of elements you have to do a bit of byte arithmetic:
    8bit = 1byte
    16bit = 2bytes
    32bit = 4 bytes
    64bit = 8 bytes

    so to get the number of elements you could do:

     numb_of_elements = ( sizeof(X)/sizeof(X[0]) );
    

    resulting in:

    uint32_t source[100]={0};
    memcpy((void*) dest, (void*) source, ( sizeof(source)/sizeof(source[0]) ));
    

    of course you would probably want to make ( sizeof(X)/sizeof(X[0]) ) a constant/variable so that you don't compute each time.. ( I don't know if compilers will always optimize this)

提交回复
热议问题