memcpy with startIndex?

后端 未结 9 1246
星月不相逢
星月不相逢 2020-12-24 11:31

I wish to copy content of specific length from one buffer to another from a specific starting point. I checked memcpy() but it takes only the length of content

9条回答
  •  借酒劲吻你
    2020-12-24 12:03

    Simply add the index to the address of the buffer, and pass it to memcpy() as the source parameter, e.g. copy from 3rd item of buffer b

    char a[10], b[20];
    ::memcpy(a,b+2,10);
    

    Also take into account the type of items in the buffer, length (3rd) parameter of memcpy() is in bytes, so to copy 4 ints you shall put 4*sizeof(int) - which will probably be 16 (on a 32 bit system. But the type does not matter for the start address, because of pointer arithmetics:

    int a[10], b[10];
    ::memcpy( a+2, b, 2*sizeof(int) );
    // a+2 will be address of 3rd item in buffer a
    // not address of 1st item + 2 bytes
    

提交回复
热议问题