memcpy with startIndex?

后端 未结 9 1155
星月不相逢
星月不相逢 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:07

    I always prefer the syntax

    memcpy( &dst[dstIdx], &src[srcIdx], numElementsToCopy * sizeof( Element ) );
    
    0 讨论(0)
  • 2020-12-24 12:10

    You could have a function like below.

    template<typename T>
    T* memcopy_index(T* dst,T* src,unsigned int index, unsigned int element_count)
    {
        return (T*)memcpy(dst,src + index, element_count * sizeof(T));
    }
    

    It can be used as below:

    int src[]={0,1,2,3,4,5,6};
    int dst[15];
    
    memcopy_index(dst,src,2,5);    //copy 5 elements from index 2
    

    You have to make sure that destination buffer has enough room to copy the elements.

    0 讨论(0)
  • 2020-12-24 12:12

    Just add the offset you want to the address of the buffer.

    char abuff[100], bbuff[100];
    ....
    memcpy( bbuff, abuff + 5, 10 );
    

    This copies 10 bytes starting at abuff[5] to bbuff.

    0 讨论(0)
提交回复
热议问题