简体   繁体   English

如何迭代指向void的指针数组

[英]How to iterate on array of pointers to void

I want to do a function that is able of shift array elements but the arrays can be of ints or of a struct defined by me. 我想做一个能够移位数组元素的函数,但是数组可以是int或由我定义的struct。 How do I iterate on pointers to void arrays? 如何迭代指向void数组的指针?

This is my code so far for this example I'm using Ints but I plan to use the same function with other data types: 这是我的代码到目前为止这个例子我正在使用Ints但我计划使用与其他数据类型相同的函数:

void shift(const void *source, int pos, int lenght){

    memmove(&source[pos], &source[pos+1], sizeof(int)*(lenght-pos-1) );
}

int main(int argc, char *argv[]) {
    int a[10] = {1,2,3,4,5,6};
    shift(a, 3, 10);

}

All you need to do to make this work across arbitrary data types is to pass the size of the data as well. 要使这项工作跨越任意数据类型,您需要做的就是传递数据的大小。 This will let you calculate the offset. 这将让您计算偏移量。 For example, 例如,

void shift(void *source, size_t size, int pos, int length){
    int src_offset =  pos * size;
    int dst_offset = (pos + 1) * size;
    memmove(source + src_offset, source + dst_offset, size*(length-pos-1) );
}

Now you can use different data types like so 现在您可以使用不同的数据类型

int main(int argc, char *argv[]) {
    // ints
    int a[10] = {1,2,3,4,5,6};
    shift(a, sizeof(int), 3, 10);

     // chars
    char b[10] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'};
    shift(b, sizeof(char), 3, 10);

     //etc...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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