0

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);

}
4
  • What do you mean by "void arrays"? Arrays which do not hold any values? Commented Apr 3, 2019 at 0:42
  • 1
    In C the [..] operator acts as a dereference. You cannot dereference a void type. Your only real option is to cast everything to char* along with the sizeof (your_type) and adjust the indexing as required. Commented Apr 3, 2019 at 0:59
  • By void arrays I meant an array whose elements as void* Commented Apr 3, 2019 at 1:58
  • 2
    If you had an array of void * you would have a variable of type void **, but that's not what you have. You need to show exactly how this function is called. Please update your question with a minimal reproducible example. Commented Apr 3, 2019 at 2:10

1 Answer 1

3

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...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for help. I tried to run it on macOS and it works for the char array but no for the int array. For int array it gives ([0] = 33554433, [1] = 50331648, [2] = 67108864, [3] = 83886080, [4] = 100663296, [5] = 0, [6] = 0, [7] = 0, [8] = 0, [9] = 0). Also the compiler gives: warning: arithmetic on a pointer to void is a GNU extension

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.