Pointers/Memory Allocation   «Prev  Next»
Lesson 7 Generic pointer type
Objective Generic pointer type as a formal parameter

void* as Formal Parameter in C++

Write a function that casts the generic pointer type void* to a standard working type

A key use for the generic pointer type is as a formal parameter. For example, the library function memcpy is declared in cstring as:

void* memcpy(void* s1, void* s2, size_t n);

On older C++ systems and on C systems, memcpy is found in string.h. The function memcpy copies n characters from the variable based at s2 into the variable based at s1. It works with any two pointer types as actual arguments. The type size_t is defined in stddef.h, and is often a synonym for unsigned int.

C++ How to Program
#include <cstring>
void *memcpy(void *to, const void *from, size_t count);

The memmove( ) function copies count characters from the array pointed to by from into the array pointed to by to. If the arrays overlap, the copy will take place correctly, placing the correct contents into the "to" destination, but leaving the "from" source modified. The memmove( ) function returns a pointer to to. A related function is memcpy( ).

Wide-Character Array Functions

The standard character array-manipulation functions, such as memcpy( ), also have wide-character equivalents.
They are shown in Figure 4-7. These functions use the header <cwchar>.

The Wide-Character Array Functions
Figure 4-7: Wide-Character Array Functions

Generic Poitner Type - Exercise

Click the Exercise link below to write and test a function that casts the generic pointer type to a standard working type.
Generic Pointer Type - Exercise