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

前端 未结 12 2153
灰色年华
灰色年华 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);
    
    $> 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)

    0 讨论(0)
  • 2020-12-09 09:59

    How about?

    memcpy(dst, src, &src[ARRAY_LENGTH] - &src[0]);
    

    This should work even if the size of individual elements was smaller than the size taken by each item in the actual array.

    0 讨论(0)
  • 2020-12-09 10:02

    Assuming dst is of type int*, sizeof(dst) will return the size of the pointer itself (i.e. 4 on a 32 bit system, 8 on a 64 bit system), so your second example will only every copy this many bytes, while the first one will correctly use the actual size of the content.

    0 讨论(0)
  • 2020-12-09 10:04

    As long as dst is declared as an array with a size, sizeof will return the size of that array in bytes:

    int dst[ARRAY_LENGTH];
    
    memcpy( dst, src, sizeof(dst) ); // Good, sizeof(dst) returns sizeof(int) * ARRAY_LENGTH
    

    If dst just happens to be a pointer to the first element of such an array (which is the same type as the array itself), it wont work:

    int buffer[ARRAY_LENGTH];
    int* dst = &buffer[0];
    
    memcpy( dst, src, sizeof(dst) ); // Bad, sizeof(dst) returns sizeof(int*)
    
    0 讨论(0)
  • 2020-12-09 10:04

    sizeof(dst) is correct only if dst is an array which size is known at compile time: like int arr[ARRAY_LENGTH] or a C99 variable length array; otherwise it returns the size of a pointer, not the length of the destination array.

    To avoid future bug, be consistent and prefer the first form: size of type * length.

    0 讨论(0)
  • 2020-12-09 10:04

    Will the second option always work? Regardless of the content?

    It will work only if both conditions are satisfied:

    • dst is regular array, not pointer
    • src and dst are the same size
    0 讨论(0)
提交回复
热议问题