简体   繁体   中英

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. How do I iterate on pointers to void arrays?

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:

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...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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