Void Pointers

Library routines such as malloc, memcpy and qsort have to work on memory of any type: integers, doubles, and structs that did not exist when the library was written. C gives them one pointer type for the job. A void pointer, written void *, holds an address but says nothing about what is stored there. This lesson covers what you can do with one, what you cannot, and how generic code recovers the type it needs.

What a void pointer can and cannot do

Any object pointer converts to void * and back again without losing the address. In C both conversions are implicit, so no cast is required; C++ does require a cast for the conversion back. The cost of that flexibility is that the compiler no longer knows the size or layout of the pointee. Because void is an incomplete type, you cannot dereference a void pointer, and ISO C does not define arithmetic on it.


C
double samples[3] = {2.5, 3.0, 4.5};
void *vp = samples;      /* any object pointer converts implicitly */
double *dp = vp;         /* and converts back without a cast in C */
printf("%.1f\n", dp[1]); /* prints 3.0 */
/* vp[1] or *vp would not compile: the pointee has no type */


Operation

double *dp

void *vp

Store an address

Yes

Yes

Accept any object pointer without a cast

No

Yes

Dereference with * or a subscript

Yes, reads sizeof(double) bytes

No

Add 1

Moves sizeof(double) bytes

Not defined in ISO C


Recovering the type with a cast

Pointer arithmetic scales by the size of the pointee. To step through memory generically, convert the void pointer to char * or unsigned char *. Since sizeof(char) is 1 by definition, each step is one byte, and you multiply by the element size yourself.


address of element i=base+i×size\text{address of element } i = \text{base} + i \times \text{size}


Example: An array of 12-byte records starts at address 0x2000. Element 3 sits 3 × 12 = 36 bytes along, which is 0x24 in hexadecimal, so its address is 0x2024.


C
void *nth(void *base, size_t i, size_t size)
{
    return (unsigned char *)base + i * size;
}


Here size arrives from the caller as a size_t argument, usually written sizeof(arr[0]). The figure shows why the cast matters: one step from the same address covers a different number of bytes depending on the pointer type you choose.


A row of twelve byte cells with a void pointer at the first byte and three arrows showing one-step moves of 1, 4 and 8 bytes.



Who knows the real type

A void pointer moves responsibility for the type from the compiler to you. A function that receives void * must learn the type, the size or both from an argument, a callback or a documented contract. When it converts back, the cast must name the type actually stored at that address; reading a double through an int * compiles but is undefined behaviour.


The comparison callback for qsort shows the pattern. qsort passes the callback two const void * arguments because it cannot know the element type; a callback written for doubles restores it:


C
int cmp_double(const void *a, const void *b)
{
    double x = *(const double *)a;
    double y = *(const double *)b;
    return (x > y) - (x < y);
}



What to remember

  • A void * stores any object address but carries no type, size or layout.
  • In C, conversion to and from void * is implicit; C++ needs a cast back.
  • You cannot dereference a void *, and arithmetic on it is a GCC extension, not ISO C.
  • For byte offsets, cast to char * or unsigned char * and compute base + i × size.
  • The code that converts back must use the type actually stored there.

Example: Locating records through a void pointer

A weather station logs readings in an array of struct reading, and on the target machine sizeof(struct reading) is 16 bytes. The array starts at address 0x7ffc0040. A generic storage library receives the array only as void *base plus the element size, and locates elements with this helper:


C
void *elem_at(void *base, size_t i, size_t size)
{
    return (char *)base + i * size;
}


The library also swaps two elements with a byte-wise helper:


C
void swap_bytes(void *a, void *b, size_t size)
{
    unsigned char tmp[64];  /* caller guarantees size is at most 64 */
    memcpy(tmp, a, size);
    memcpy(a, b, size);
    memcpy(b, tmp, size);
}


a) What address does elem_at(base, 6, 16) return? Give it in hexadecimal.


The cast to char * makes each step of pointer arithmetic one byte, because sizeof(char) is 1. The offset is therefore 6 × 16 = ________, which is ________ in hexadecimal.


address=0x7ffc0040+0x60=0x7ffc00a0\text{address} = \text{0x7ffc0040} + \text{0x60} = \text{0x7ffc00a0}


The helper returns 0x7ffc00a0, the start of element 6, which is the seventh record.


b) A teammate shortens the helper body to return (int *)base + i * size;. With a 4-byte int, what address does the same call return, and which record does it land on?


The arithmetic is now on an int *, so the compiler scales the offset by sizeof(int). The expression adds 6 × 16 = 96 elements of 4 bytes each, a byte offset of ________, which is ________ in hexadecimal.


address=0x7ffc0040+0x180=0x7ffc01c0\text{address} = \text{0x7ffc0040} + \text{0x180} = \text{0x7ffc01c0}


The call returns 0x7ffc01c0. Dividing 384 by the 16-byte record size gives ________, so the pointer lands at the start of element 24 instead of element 6. If the array holds fewer than 25 records, the pointer is out of bounds and using it is undefined behaviour. The caller already multiplied by the element size, so the cast must be to a one-byte type such as char *.


c) How many bytes does one call to swap_bytes with size 16 copy in total, and why must the caller pass size?


The helper makes ________ calls to memcpy, each moving 16 bytes: the first element into the buffer, the second element into the first, and the buffer into the second. The total is 3 × 16 = 48 bytes.


The size argument is essential because a void * carries no type information. Inside swap_bytes, the expression *a has type void, so the function cannot use sizeof(*a) to find the element size. Only the caller knows the element type, so it passes sizeof(struct reading), which is 16 here.

A student stores four counts in an array and passes them around through a void *, but the compiler rejects the last line of this fragment:


C
int counts[4] = {7, 3, 9, 1};
void *vp = counts;
int first = *vp;


Which replacement for the last line reads the first element correctly on any conforming C implementation?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

An array of double values starts at memory address 4000 (written in decimal), and sizeof(double) is 8 on this machine. A generic routine receives the array as void *vp and calls elem_at(vp, 7, sizeof(double)), where elem_at returns (char *)base + i * size. What address does the call return? Give the address in decimal as a whole number.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A void *vp holds the address 1000 (written in decimal). On this machine char, short, int and double occupy 1, 2, 4 and 8 bytes respectively. For each row, the pointer is first cast to a pointer to the named type and then 5 is added using ordinary pointer arithmetic. Enter the resulting address in decimal.

Cast applied to vp, then add 5Resulting address (decimal)
char pointer
short pointer
int pointer
double pointer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors