Search Menu



Problem : Why can't you dereference a void pointer?

Whereas most pointers have a type associated with them, and thus a size, void pointers can point to anything. When a computer dereferences a pointer, it checks the type to see how many bytes forward from the address pointed to it needs to look. But with a void pointer, which has no specific byte size associated with it, the computer has no idea what to look at, nor would it know how to interpret the data even if it did know the size.

Problem : Given the function: void print_bit_int(int value); which takes an integer as a parameter and prints out its bit representation, write a line of code which prints out the bit representation for a float spark (you can assume that a float is the same size as an integer).


Problem : Write a function, memcmp(), which takes two void pointers and a length in bytes, and compares the memory at those two locations for that many bytes. It should return a non-zero value if the memory matches, and zero if the memory does not match.

int memcmp(void* m1, void* m2, int len)
	char *c1 = (char*)m1;
	char *c2 = (char*)m2;
	for(;len>0; len--) if (*m1 != *m2) return 0;
	return 1;

Problem : What is wrong with the following code? How would you fix it with a cast?

int main()
	int steve;
	int *spark;
	void *notes;

	steve = 500;
	spark = &steve;
	notes = (void*)spark;

	*notes = 600;
	printf("%d\n", steve);
	return 0;

The problem is that we're dereferencing a void pointer when we attempt to do *notes = 600;. To fix it, we'll need to cast notes to be an integer pointer before we dereference it, as in *(int *)notes = 600;.

Problem : What is wrong with the following code?

int main()
	int a, b;
	double d, e 
	void* v[10];
	v[0] = &a;
	v[1] = &d;
	v[2] = &b;
	v[3] = &e;

	int x = *((int*)v[0]);
	double w = *((double*)v[1]); 
	int y = *((int*)v[1]);
	return 0;

The line int y = *((int*)v[1]); is a problem. If you'll look above, you'll see that we've stored the address of the double d into v[1]. However, this next to last line treats it as an integer.