11684
11684

Reputation: 7517

How to edit a void type array

How does one edit void pointers? Obviously, this is possible in C, because there are many standard library functions that do this.

I thought I'd implement a function swapping two array elements (I know there is a standard function for it, it's just an exercise), so ideally I'd want to do this:

void swap(void *arr, int a, int b, int elSize) {
    void arrEl = arr[a];
    arr[a] = arr[b];
    arr[b] = arrEl;
}

Of course, I can't dereference a void pointer, nor can I have a variable of type void, so I have to work around that somehow, but I discovered I don't know how to edit a void type array.
So how should I implement above pseudo-C?

I saw this thread, but I am not sure how to apply that and think seeing the correct version of above pseudo-C will make it a bit more clear.

Upvotes: 0

Views: 861

Answers (3)

Some programmer dude
Some programmer dude

Reputation: 409482

Technically you can't have a void array or void values. You can have a void pointer that points to an array of some type.

To use it you have to cast it to a non-void pointer, like e.g.

int value0 = ((int *) arr)[0];

And the simplest solution to not have to do this is to declare the pointer arr as a pointer to the type it actually is.

If you can't do that, then if you have the element size, you can declare temporary variable-length arrays to handle the swapping, like

char tmp[elSize];

memcpy(tmp, (char *) arr + elSize * a, elSize);
memcpy((char *) arr + elSize * a, (char *) arr + elSize * b, elSize);
memcpy((char *) arr + elSize * b, tmp, elSize);

The above swaps between the values at "index" a and b.

Upvotes: 1

wildplasser
wildplasser

Reputation: 44250

Joachim was a bit faster, but I'll add my answer anyway.

#include <string.h>

void swap(void *arr, size_t a, size_t b, size_t elSize) {
    char temp[elSize];

    memcpy(temp, (char*)arr+a*elSize, elSize);
    memcpy((char*)arr+a*elSize, (char*)arr+b*elSize, elSize);
    memcpy((char*)arr+b*elSize, temp, elSize);
}

#include <stdio.h>
int main(void)
{

int array[3] = {1,13,42};

char text[] = "This is text\n" ;

swap(text, 0, 2, 4);

printf("%s", text );

swap(array, 0, 2, sizeof array[0] );

printf("{%d %d %d}\n", array[0], array[1], array[2] );

return 0;
}

Upvotes: 1

haccks
haccks

Reputation: 106132

By assigning arr[a] to arrEl, in fact you are dereferencing a void type pointer. And for this you must have to cast it before doing any operation to it. As;

int arrEl = ((int *)arr)[a];  

or

int arrEl = *((int *)arr + a); 

Upvotes: 0

Related Questions