I am learning C from "C by K&R". I was going through Function pointers section.There was an example to sort an array of strings using function pointers and void pointers.(to be specific,on page 100). I have a fair understanding of function pointers and void pointers.
The example given there calls
qsort((void**) lineptr, 0, nlines-1,(int (*)(void*,void*))(numeric ? numcmp : strcmp));
And it seemlessly uses void ptr,like as below to compare and swap.
I understand that it takes array of pointer and each element by itself is a void pointer to the string. How is it possible to compare,swap a void ptr with another.
void sort(void *v[],int i,int j)
{
id *temp;
temp = v[i];
v[i] = v[j];
v[j] = temp;
}
Can anyone explain the concept behind this.
How is it possible to compare, swap a void ptr with another?
Compare: comparing a void ptr with each other is meaningless, as their values are addresses.
Swap: A pointer is a variable holding an address. By changing a pointer's value you change the address it points to. Data itself is not even considered here.
Note: void pointers does not interpret the data they are pointing to. That is why you need explicit type conversion when you dereference them, such that there is a correspondence between the data they are pointing to and the variable this data is assign to.
Remember that pointers are just variables that store a memory address. If there's not any conflict between types I can't see why this shouldn't be possible!
The only difference between a void ptr and another is that you must pay attention only during the dereference (you need a cast to complete it)
For example:
void *ptr;
int m, n;
ptr = &n;
m = *((int *) ptr);
Anyway, ignoring this particular, you can work with void pointer normally.. You can, as your code shows, for example swap them just as they were int or other types variables
The function pointer required by qsort() has the following type
int (*compar)(const void *, const void *);
it means, that you can pass pointers of any type to this function since in c void * is converted to any poitner type without a cast.
Inside a comparision funcion, you MUST "cast"1 the void * poitners in order to be able to dereference them. Because a void * pointer cannot be dereferenced.
Swaping pointers is the correct way to sort an array of poitners, just like swaping integers would be the way to sort an array of integers. The other way, with an array of strings for example, would be to copy the string to a temporary buffer and perform a swap in terms of copying the data, and I think there is no need to explain why this is bad.
1
When I say cast I don't mean that you need to "cast", just convert to the appropriate poitner type. For example:
int compare_integers(const void *const x, const void *const y)
{
int *X;
int *Y;
X = x;
Y = y;
return (*X - *Y);
}
although it's of course possible to write return (*((int *) x) - *((int *) y)).
In this type of situation, it's often helpful to typedef to gain a better understanding. For illustration purposes, you could do
typedef void* address; //to emphasize that a variable of type void* stores an address
Now your swap function looks less daunting,
void swap(address v[],int i,int j) //takes an array of addresses v
{
address temp;
temp = v[i];
v[i] = v[j];
v[j] = temp;
}
A void *, however, contains no information regarding the type of object it points to. So before dereferencing it, you need to cast it to the right type, which is what strcmp and numcmp do, e.g.,
int strcmp(address a1, address a2) { //assumes a1 and a2 store addresses of strings
char *s1 = a1;
char *s2 = a2;
//s1 and s2 can be dereferenced and the strings they point to can be compared
}
Related
This question already has answers here:
Swapping objects using pointers
(10 answers)
Closed 7 years ago.
I want to make a swap function that can be generically used for any data type. I know that the following function works for ints:
void swap(void *a, void *b)
{
int temp;
temp = *(int*)a;
*(int*)a = *(int*)b;
*(int*)b = temp;
}
and this works for strings:
void swap(void *a, void *b)
{
void *temp;
temp = *(void**)a;
*(void**)a = *(void**)b;
*(void**)b = temp;
}
If you pass the size of the pointee along, too (like in qsort), then you can do it:
void swap(void * a, void * b, size_t len)
{
unsigned char * p = a, * q = b, tmp;
for (size_t i = 0; i != len; ++i)
{
tmp = p[i];
p[i] = q[i];
q[i] = tmp;
}
}
Usage:
struct Qux x, y;
swap(&x, &y, sizeof(Qux));
(You might want to add restrict qualifiers to the pointers, or otherwise a test for self-swapping.)
You should read the C FAQ list at least once. It is good to see what people have pondered over time.
Why can't I perform arithmetic on a void * pointer? is relevant to your question:
The compiler doesn't know the size of the pointed-to objects. (Remember that pointer arithmetic is always in terms of the pointed-to size; see also question 4.4.) Therefore, arithmetic on void *'s is disallowed (though some compilers allow it as an extension). Before performing arithmetic, convert the pointer either to char * or to the pointer type you're trying to manipulate (but see also questions 4.5 and 16.7).
Also relevant is Suppose I want to write a function that takes a generic pointer as an argument and I want to simulate passing it by reference. Can I give the formal parameter type void ** ...:
There is no generic pointer-to-pointer type in C. void * acts as a generic pointer only because conversions (if necessary) are applied automatically when other pointer types are assigned to and from void *'s; these conversions cannot be performed if an attempt is made to indirect upon a void ** value which points at a pointer type other than void *. When you make use of a void ** pointer value (for instance, when you use the * operator to access the void * value to which the void ** points), the compiler has no way of knowing whether that void * value was once converted from some other pointer type. It must assume that it is nothing more than a void *; it cannot perform any implicit conversions.
Here's another answer:
void swap(void *a, void *b, size_t width)
{
void *temp = malloc(width);
memcpy(temp, b, width);
memcpy(b, a, width);
memcpy(a, temp, width);
free(temp);
}
I have the following struct:
struct Map {
void* arr; // includes pointers to certain blocks of memory
int mem_block_count;
};
The void* arr holds pointers to certain cells in memory. Each cell holds a void* pointer to another cell in memory (as a linked list) a char* string, and a value with its own size.
You should be able to grab one of these pointers to a cell by doing arr[i] where i is an index - is this right?
I am trying to access the first pointer to one of these cells, which is probably arr[0]. Then, I want to get access to the pointer to the next cell in memory. But this is of void type. So how do I get at it? For getting access to the char*, I just move forward in memory, and then do a strcpy. But how do I get access/deref the next pointer?
EDIT: I also thought about casting the void pointer to an int, but I'm not sure I would get the right value. Something like:
int *next_pointer;
next_pointer = (int*) map->arr[i]
But is this not preserving the pointer to the pointer when I cast this as an int? How do I dereference a pointer to a pointer correctly?
EDIT - Couldn't I also, because it is a linked list of pointers, also do something like - map->arr + index * sizeof(void*) to get to the start of a given cell?
You can't use array indexing on a void pointer, as it really just a generic pointer without a type. And if there's no type then there's no way of adding the correct offset to the base memory address. You have to cast it to the correct structure before using array indexing:
((struct some_structure *) arr)[1]
You need pointers to pointers.
#include <stdio.h>
#include <stdlib.h>
struct Map {
void **arr; // includes pointers to certain blocks of memory
int mem_block_count;
};
int main(void) {
struct Map map = {0};
int a1[100];
double a2[100];
char a3[100];
map.arr = malloc(3 * sizeof *map.arr);
if (!map.arr) /* error */;
a1[42] = 42;
a2[42] = 42;
a3[42] = 42;
map.mem_block_count = 3;
map.arr[0] = a1;
map.arr[1] = a2;
map.arr[2] = a3;
printf("%d %f %c\n", ((int *)(map.arr[0]))[42],
((double *)(map.arr[1]))[42],
((char *)(map.arr[2]))[42]);
free(map.arr);
return 0;
}
Is it possible to dereference a void pointer without type-casting in the C programming language?
Also, is there any way of generalizing a function which can receive a pointer and store it in a void pointer and by using that void pointer, can we make a generalized function?
for e.g.:
void abc(void *a, int b)
{
if(b==1)
printf("%d",*(int*)a); // If integer pointer is received
else if(b==2)
printf("%c",*(char*)a); // If character pointer is received
else if(b==3)
printf("%f",*(float*)a); // If float pointer is received
}
I want to make this function generic without using if-else statements - is this possible?
Also if there are good internet articles which explain the concept of a void pointer, then it would be beneficial if you could provide the URLs.
Also, is pointer arithmetic with void pointers possible?
Is it possible to dereference the void pointer without type-casting in C programming language...
No, void indicates the absence of type, it is not something you can dereference or assign to.
is there is any way of generalizing a function which can receive pointer and store it in void pointer and by using that void pointer we can make a generalized function..
You cannot just dereference it in a portable way, as it may not be properly aligned. It may be an issue on some architectures like ARM, where pointer to a data type must be aligned at boundary of the size of data type (e.g. pointer to 32-bit integer must be aligned at 4-byte boundary to be dereferenced).
For example, reading uint16_t from void*:
/* may receive wrong value if ptr is not 2-byte aligned */
uint16_t value = *(uint16_t*)ptr;
/* portable way of reading a little-endian value */
uint16_t value = *(uint8_t*)ptr
| ((*((uint8_t*)ptr+1))<<8);
Also, is pointer arithmetic with void pointers possible...
Pointer arithmetic is not possible on pointers of void due to lack of concrete value underneath the pointer and hence the size.
void* p = ...
void *p2 = p + 1; /* what exactly is the size of void?? */
In C, a void * can be converted to a pointer to an object of a different type without an explicit cast:
void abc(void *a, int b)
{
int *test = a;
/* ... */
This doesn't help with writing your function in a more generic way, though.
You can't dereference a void * with converting it to a different pointer type as dereferencing a pointer is obtaining the value of the pointed-to object. A naked void is not a valid type so derefencing a void * is not possible.
Pointer arithmetic is about changing pointer values by multiples of the sizeof the pointed-to objects. Again, because void is not a true type, sizeof(void) has no meaning so pointer arithmetic is not valid on void *. (Some implementations allow it, using the equivalent pointer arithmetic for char *.)
You should be aware that in C, unlike Java or C#, there is absolutely no possibility to successfully "guess" the type of object a void* pointer points at. Something similar to getClass() simply doesn't exist, since this information is nowhere to be found. For that reason, the kind of "generic" you are looking for always comes with explicit metainformation, like the int b in your example or the format string in the printf family of functions.
A void pointer is known as generic pointer, which can refer to variables of any data type.
So far my understating on void pointer is as follows.
When a pointer variable is declared using keyword void – it becomes a general purpose pointer variable. Address of any variable of any data type (char, int, float etc.)can be assigned to a void pointer variable.
main()
{
int *p;
void *vp;
vp=p;
}
Since other data type pointer can be assigned to void pointer, so I used it in absolut_value(code shown below) function. To make a general function.
I tried to write a simple C code which takes integer or float as a an argument and tries to make it +ve, if negative. I wrote the following code,
#include<stdio.h>
void absolute_value ( void *j) // works if used float, obviously it must work but thats not my interest here.
{
if ( *j < 0 )
*j = *j * (-1);
}
int main()
{
int i = 40;
float f = -40;
printf("print intiger i = %d \n",i);
printf("print float f = %f \n",f);
absolute_value(&i);
absolute_value(&f);
printf("print intiger i = %d \n",i);
printf("print float f = %f \n",f);
return 0;
}
But I was getting error, so I came to know my understanding with void pointer is not correct :(. So now I will move towards to collect points why is that so.
The things that i need to understand more on void pointers is that.
We need to typecast the void pointer variable to dereference it. This is because a void pointer has no data type associated with it. There is no way the compiler can know (or guess?) what type of data is pointed to by the void pointer. So to take the data pointed to by a void pointer we typecast it with the correct type of the data holded inside the void pointers location.
void main()
{
int a=10;
float b=35.75;
void *ptr; // Declaring a void pointer
ptr=&a; // Assigning address of integer to void pointer.
printf("The value of integer variable is= %d",*( (int*) ptr) );// (int*)ptr - is used for type casting. Where as *((int*)ptr) dereferences the typecasted void pointer variable.
ptr=&b; // Assigning address of float to void pointer.
printf("The value of float variable is= %f",*( (float*) ptr) );
}
A void pointer can be really useful if the programmer is not sure about the data type of data inputted by the end user. In such a case the programmer can use a void pointer to point to the location of the unknown data type. The program can be set in such a way to ask the user to inform the type of data and type casting can be performed according to the information inputted by the user. A code snippet is given below.
void funct(void *a, int z)
{
if(z==1)
printf("%d",*(int*)a); // If user inputs 1, then he means the data is an integer and type casting is done accordingly.
else if(z==2)
printf("%c",*(char*)a); // Typecasting for character pointer.
else if(z==3)
printf("%f",*(float*)a); // Typecasting for float pointer
}
Another important point you should keep in mind about void pointers is that – pointer arithmetic can not be performed in a void pointer.
void *ptr;
int a;
ptr=&a;
ptr++; // This statement is invalid and will result in an error because 'ptr' is a void pointer variable.
So now I understood what was my mistake. I am correcting the same.
References :
http://www.antoarts.com/void-pointers-in-c/
http://www.circuitstoday.com/void-pointers-in-c.
The New code is as shown below.
#include<stdio.h>
#define INT 1
#define FLOAT 2
void absolute_value ( void *j, int *n)
{
if ( *n == INT) {
if ( *((int*)j) < 0 )
*((int*)j) = *((int*)j) * (-1);
}
if ( *n == FLOAT ) {
if ( *((float*)j) < 0 )
*((float*)j) = *((float*)j) * (-1);
}
}
int main()
{
int i = 0,n=0;
float f = 0;
printf("Press 1 to enter integer or 2 got float then enter the value to get absolute value\n");
scanf("%d",&n);
printf("\n");
if( n == 1) {
scanf("%d",&i);
printf("value entered before absolute function exec = %d \n",i);
absolute_value(&i,&n);
printf("value entered after absolute function exec = %d \n",i);
}
if( n == 2) {
scanf("%f",&f);
printf("value entered before absolute function exec = %f \n",f);
absolute_value(&f,&n);
printf("value entered after absolute function exec = %f \n",f);
}
else
printf("unknown entry try again\n");
return 0;
}
Thank you,
No, it is not possible. What type should the dereferenced value have?
void abc(void *a, int b) {
char *format[] = {"%d", "%c", "%f"};
printf(format[b-1], a);
}
Here is a brief pointer on void pointers: https://www.learncpp.com/cpp-tutorial/613-void-pointers/
6.13 — Void pointers
Because the void pointer does not know what type of object it is pointing to, it cannot be dereferenced directly! Rather, the void pointer must first be explicitly cast to another pointer type before it is dereferenced.
If a void pointer doesn't know what it's pointing to, how do we know what to cast it to? Ultimately, that is up to you to keep track of.
Void pointer miscellany
It is not possible to do pointer arithmetic on a void pointer. This is because pointer arithmetic requires the pointer to know what size object it is pointing to, so it can increment or decrement the pointer appropriately.
Assuming the machine's memory is byte-addressable and does not require aligned accesses, the most generic and atomic (closest to the machine level representation) way of interpreting a void* is as a pointer-to-a-byte, uint8_t*. Casting a void* to a uint8_t* would allow you to, for example, print out the first 1/2/4/8/however-many-you-desire bytes starting at that address, but you can't do much else.
uint8_t* byte_p = (uint8_t*)p;
for (uint8_t* i = byte_p; i < byte_p + 8; i++) {
printf("%x ",*i);
}
I want to make this function generic,
without using ifs; is it possible?
The only simple way I see is to use overloading .. which is not available in C programming langage AFAIK.
Did you consider the C++ programming langage for your programm ? Or is there any constraint that forbids its use?
Void pointers are pointers that has no data type associated with it.A void pointer can hold address of any type and can be typcasted to any type. But, void pointer cannot be directly be dereferenced.
int x = 1;
void *p1;
p1 = &x;
cout << *p1 << endl; // this will give error
cout << (int *)(*p) << endl; // this is valid
You can easily print a void printer
int p=15;
void *q;
q=&p;
printf("%d",*((int*)q));
Because C is statically-typed, strongly-typed language, you must decide type of variable before compile. When you try to emulate generics in C, you'll end up attempt to rewrite C++ again, so it would be better to use C++ instead.
void pointer is a generic pointer.. Address of any datatype of any variable can be assigned to a void pointer.
int a = 10;
float b = 3.14;
void *ptr;
ptr = &a;
printf( "data is %d " , *((int *)ptr));
//(int *)ptr used for typecasting dereferencing as int
ptr = &b;
printf( "data is %f " , *((float *)ptr));
//(float *)ptr used for typecasting dereferencing as float
You cannot dereference a pointer without specifying its type because different data types will have different sizes in memory i.e. an int being 4 bytes, a char being 1 byte.
Fundamentally, in C, "types" are a way to interpret bytes in memory. For example, what the following code
struct Point {
int x;
int y;
};
int main() {
struct Point p;
p.x = 0;
p.y = 0;
}
Says "When I run main, I want to allocate 4 (size of integer) + 4 (size of integer) = 8 (total bytes) of memory. When I write '.x' as a lvalue on a value with the type label Point at compile time, retrieve data from the pointer's memory location plus four bytes. Give the return value the compile-time label "int.""
Inside the computer at runtime, your "Point" structure looks like this:
00000000 00000000 00000000 00000000 00000000 00000000 00000000
And here's what your void* data type might look like: (assuming a 32-bit computer)
10001010 11111001 00010010 11000101
This won't work, yet void * can help a lot in defining generic pointer to functions and passing it as an argument to another function (similar to callback in Java) or define it a structure similar to oop.
I'm beginning to learn C and read following code:
public void** list_to_array(List* thiz){
int size = list_size(thiz);
void **array = malloc2(sizeof(void *) * size);
int i=0;
list_rewind(thiz);
for(i=0; i<size; i++){
array[i] = list_next(thiz);
}
list_rewind(thiz);
return array;
}
I don't understand the meaning of void**. Could someone explain it with some examples?
void** is a pointer to a pointer to void (unspecified type). It means that the variable (memory location) contains an address to a memory location, that contains an address to another memory location, and what is stored there is not specified. In this question's case it is a pointer to an array of void* pointers.
Sidenote: A void pointer can't be dereferenced, but a void** can.
void *a[100];
void **aa = a;
By doing this one should be able to do e.g. aa[17] to get at the 18th element of the array a.
To understand such declarations you can use this tool and might as well check a related question or two.
void** is a pointer to void*, or a pointer to a void pointer if you prefer!
This notation is traditionally used in C to implement a matrix, for example. So, in the matrix case, that would be a pointer to an array of pointers.
Normally void * pointers are used to denote a pointer to an unknown data type. In this case your function returns an array of such pointers thus the double star.
In C, a pointer is often used to reference an array. Eg the following assignment is perfectly legal:
char str1[10];
char *str2 = str1;
Now when void is used, it means that instead of char you have a variable of unknown type.
Pointers to an unknown data type are useful for writing generic algorithms. Eg. the qsort function in standard C library is defined as:
void qsort ( void * base,
size_t num,
size_t size,
int ( * comparator )
( const void *, const void * ) );
The sorting algorithm itself is generic, but has no knowledge of the contents of the data. Thus the user has to provide an implementation of a comparator that can deal with it. The algorithm will call the comparator with two pointers to the elements to be compared. These pointers are of void * type, because there is now information about the type of data being sorted.
Take a look at this thread for more examples
http://forums.fedoraforum.org/showthread.php?t=138213
void pointers are used to hold address of any data type. void** means pointer to void pointer. Void pointers are used in a place where we want a function should receive different types of data as function argument. Please check the below example
void func_for_int(void *int_arg)
{
int *ptr = (int *)int_arg;
//some code
}
void func_for_char(void *char_arg)
{
char *ptr = (char *)char_arg;
//some code
}
int common_func(void * arg, void (*func)(void *arg))
{
func(arg);
}
int main()
{
int a = 10;
char b = 5;
common_func((void *)&a, func_for_int);
common_func((void *)&b, func_for_char);
return 0;
}
I'm trying to swap objects for a homework problem that uses void pointers to swap objects. The declaration of my function has to be:
void swap(void *a, void *b, size_t size);
I'm not looking for the exact code how to do it so I can figure it out by myself, but I'm not sure if I understand it correctly. I found that one problem is by doing:
void *temp;
temp = a;
a = b;
b = temp;
only changes what the pointers point to. Is that correct? If it is correct, why doesn't swapping pointers actually change the contents between *a and *b. Because if your pointer points to something different, couldn't you dereference it and the objects would now be different?
Similarly, just switching the values like:
void *temp;
*temp = *a;
*a = *b;
*b = *temp;
Is not correct either, which I'm not sure why. Because again, it seems to me that the content is switched.
Does swapping objects mean complete swapping of memory and value of what a pointer points to?
So it seems like I have to use malloc to allocate enough space for my swap. If I allocate enough memory for one object, assuming they are the same size, I don't really see how it is different than the other two methods above.
void *temp = malloc(sizeof(pa));
// check for null pointer
temp = a;
// do something I'm not sure of since I don't quite get how allocating space is any
// different than the two above methods???
Thanks!
Swapping pointers does not change the pointed-to values. If it did, that would be like swapping address labels on envelopes moving me into your house and you into mine.
You were nearly there:
void swap(void *a, void *b, size_t size) {
char temp[size]; // C99, use malloc otherwise
// char serves as the type for "generic" byte arrays
memcpy(temp, b, size);
memcpy(b, a, size);
memcpy(a, temp, size);
}
The memcpy function copies memory, which is the definition of objects in C. (Called POD or plain ol' data in C++, to compare.) In this way, memcpy is how you do assignment without caring about the type of the object, and you could even write other assignments as memcpy instead:
int a = 42, b = 3, temp;
temp = b;
b = a;
a = temp;
// same as:
memcpy(&temp, &b, sizeof a);
memcpy(&b, &a, sizeof a);
memcpy(&a, &temp, sizeof a);
This is exactly what the above function does, since you cannot use assignment when you do not know the type of the object, and void is the type that stands in for "unknown". (It also means "nothing" when used as function return type.)
As a curiosity, another version which avoids malloc in common cases and doesn't use C99's VLAs:
void swap(void *a, void *b, size_t size) {
enum { threshold = 100 };
if (size <= threshold) {
char temp[threshold];
memcpy(temp, b, size);
memcpy(b, a, size);
memcpy(a, temp, size);
}
else {
void* temp = malloc(size);
assert(temp); // better error checking desired in non-example code
memcpy(temp, b, size);
memcpy(b, a, size);
memcpy(a, temp, size);
free(temp);
}
}
To answer your first question, let's fill in some values to see what is happening:
void* a = 0x00001000; // some memory address
void* b = 0x00002000; // another memory address
/* Now we'll put in your code */
void* temp; // temp is garbage
temp = a; // temp is now 0x00001000
a = b; // a is now 0x00002000
b = temp; // b is now 0x00001000
So at the end of those statements, the pointer's values have been swapped, that is, whatever a was pointing to is now pointed to by b, and vice versa. The values of what those pointers are pointing to are unmodified, it's just that now their memory addresses are being held by different pointers.
To answer your second question, you cannot dereference a void*. The reason for this is that void has no size, so to try and dereference or assign to something that has no size is nonsensical. Thus, void* is a way of guaranteeing you can point to something, but you will never know what that something is without more information (hence the size parameter to your routine).
From there, knowing the pointer and the size of the data the pointer points to, you can use a routine like memcpy to move the data pointed to by one pointer into the location pointed to by another.
Parameters are like local variables, with values copied into them before the function starts executing. This prototype:
void swap(void *a, void *b, size_t size);
Means that the two addresses are copied into new variables called a and b. So if you change what is stored in a and b, nothing you do will have an any effect after swap returns.
I had a question similar to this for my C course. I think memcopy is probably best but you can also try this:
typedef unsigned char * ucp;
void swap(void *a, void *b, int size){
ucp c=(ucp)a;
ucp d=(ucp)b;
for(int i=0; i<size; i++){
int temp=(int)c[i];
c[i]=(int)d[i];
d[i]=temp;
}
}
Basically what this does is cast both pointers to an unsigned char pointer type. Then you increment the pointer, which in the case of an unsigned char, increments one BYTE at a time. Then what you're doing is basically copying the contents of each byte at a time in memory. If anyone wants to correct or clarify on this I would appreciate it too.
First of all, note that any changes to the pointers inside the function won't be propagated to outside the function. So you're going to have to move memory around.
The easiest way to do that is with memcpy - allocate a buffer on the stack, memcpy the appropriate size from a into it, memcpy from b to a, and one last memcpy from temp into b.
If you were writing a function to swap two integers, given pointers to them, your solution of swapping the values pointed to would work. However, consider the situation with
struct {
int a;
int b;
} a, b;
swap(&a, &b, sizeof(a));
You need to figure out a way to swap the contents of each value passed without any knowledge of what they actually consist of.
You're close.
The problem is: you are "swapping" only pointers a and b which are local variables in the function.
I assume outside of the function you have some variables, let's call them:
void *x = ...;
void *y = ...;
When you call:
swap(x, y, some_size);
a and b points to the same objects as x and y respectively. Now, when you swap what a and b points too, x and y are still pointing to what they where pointing before.
To change what memory x and y points you would have to pass a pointer to the x variable, so a pointer to a pointer :)
Because you can't change function declaration you can only swap the content of the memory where x (and a) and y (and b) points to. Some solutions are in other answers :) Generally memcpy is what you want.
To have any real effect, you need to do the equivalent of the second block you mentioned:
void *temp;
*temp = *a;
*a = *b;
*b = *temp;
The problem here is that 'void' doesn't have a size, so you can't assign 'void's as they stand. You need to allocate space for temp to point at, then copy the values using something like memcpy().
To change the pointer inside and keep it outside, you have to pass the pointer by reference or a double pointer.
If your function has to be like:
void swap(void *a, void *b, size_t size);
I suppose that you have to implement something like:
void * temp;
temp = malloc(size);
memcpy(temp,a,size);
memcpy(a,b,size);
memcpy(b,temp,size);
free(temp);
We need not use memcpy for swapping two pointers, following code works well(tested for swapping int* and char* strings):
void swap(void **p, void **q)
{
void *t = *p;
*p = *q;
*q = t;
}