说明
本文是个人学习用的非官方中英对照译文,原文:https://diveintosystems.org/book/C2-C_depth/advanced_voidstar.html。
原书采用 CC BY-NC-ND 4.0 许可(禁止演绎),请勿公开传播本译文。
标为「译注」「现代更新」的内容是译者补充,不代表原书作者观点;代码与原文逐字一致,未作改动。
2.9.3. The void * Type and Type Recasting
C 类型 void * 表示通用指针——指向任意类型的指针,或者说指向未指定类型的指针。C 之所以允许通用指针类型,是因为系统上的内存地址总是用相同的字节数存储(例如,在 32 位系统上地址是 4 字节,在 64 位系统上是 8 字节)。因此,每个指针变量所需的存储字节数都相同;正因为大小都一样,编译器无需知道 void * 变量所指向的类型,就能为它分配空间。下面是一个例子:
The C type
void *represents a generic pointer — a pointer to any type, or a pointer to an unspecified type. C allows for a generic pointer type because memory addresses on a system are always stored in the same number of bytes (e.g., addresses are four bytes on 32-bit systems and eight bytes on 64-bit systems). As a result, every pointer variable requires the same number of storage bytes, and because they’re all the same size, the compiler can allocate space for avoid *variable without knowing the type it points to. Here’s an example:
1 | void *gen_ptr; |
程序员通常不会像上例那样声明 void * 类型的变量。它更常用来指定函数的通用返回类型或通用参数。返回可存放任意类型的新分配内存的函数(例如 malloc),常以 void * 作为返回类型。能接收任意类型值的函数,也用它作为函数参数类型:每次调用函数时传入的是指向某种具体类型的指针,由于 void * 可以存放任意类型的地址,这个指针可以传给函数的 void * 参数。
Typically, programmers do not declare variables of type
void *as in the preceding example. Instead, it’s commonly used to specify generic return types from functions or generic parameters to functions. Thevoid *type is often used as a return type by functions that return newly allocated memory that can be used to store any type (e.g.,malloc). It’s also used as a function parameter for functions that can take any type of value. In this case, individual calls to the function pass in a pointer to some specific type, which can be passed to the function’svoid *parameter because it can store the address of any type.
由于 void * 是通用指针类型,它不能直接被解引用——编译器不知道该地址所指向的内存有多大。例如,这个地址可能指向一个 4 字节的 int 存储位置,也可能指向内存中一个 1 字节的 char 存储位置。因此,程序员必须在解引用之前,显式地把 void * 指针强制转换(recast)为指向某种具体类型的指针。强制转换告诉编译器指针变量的具体类型,使编译器能为指针解引用生成正确的内存访问代码。
Because
void *is a generic pointer type, it cannot be directly dereferenced — the compiler does not know the size of memory that the address points to. For example, the address could refer to anintstorage location of four bytes or it could refer to acharstorage location in memory of one byte. Therefore, the programmer must explicitly recast thevoid *pointer to a pointer of a specific type before dereferencing it. Recasting tells the compiler the specific type of pointer variable, allowing the compiler to generate the correct memory access code for pointer dereferences.
下面是 void * 的两个用法示例:
Here are two examples of
void *use:
调用
malloc时,把它的void *返回类型强制转换为用来存放其返回的堆内存地址的变量的具体指针类型:1
2
3
4
5
6
7
8int *array;
char *str;
array = (int *)malloc(sizeof(int) * 10); // recast void * return value
str = (char *)malloc(sizeof(char) * 20);
*array = 10;
str[0] = 'a';
A call to
mallocrecasts itsvoid *return type to the specific pointer type of the variable used to store its returned heap memory address:
1
2
3
4
5
6
7
8 int *array;
char *str;
array = (int *)malloc(sizeof(int) * 10); // recast void * return value
str = (char *)malloc(sizeof(char) * 20);
*array = 10;
str[0] = 'a';
学生常常在创建线程时遇到
void *。在线程函数中使用void *参数类型,使线程可以接收任意类型的应用特定指针。pthread_create函数有一个参数用于指定线程主函数,还有一个void *参数用于传递实参值,这个值会被传给新创建的线程要执行的线程主函数。void *参数的使用使pthread_create成为一个通用的线程创建函数:它可以指向任意类型的内存位置。对于某个调用pthread_create的具体程序,程序员知道传给void *参数的实参是什么类型,因此必须在解引用之前把它强制转换为已知的类型。在这个例子中,假设传给args参数的地址是一个整型变量的地址:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26/*
* an application-specific pthread main function
* must have this function prototype: int func_name(void *args)
*
* any given implementation knows what type is really passed in
* args: pointer to an int value
*/
int my_thr_main(void *args) {
int num;
// first recast args to an int *, then dereference to get int value
num = *((int *)args); // num gets 6
...
}
int main(void) {
int ret, x;
pthread_t tid;
x = 6;
// pass the address of int variable (x) to pthread_create's void * param
// (we recast &x as a (void *) to match the type of pthread_create's param)
ret = pthread_create(&tid, NULL,
my_thr_main, // a thread main function
(void *)(&x)); // &x will be passed to my_thr_main
// ...
Students often encounter the
void *when creating threads. Using avoid *parameter type in a thread function allows the thread to take any type of application-specific pointer. Thepthread_createfunction has a parameter for the thread main function and avoid *parameter for the argument value that it passes to the thread main function that the newly created thread will execute. The use of thevoid *parameter makespthread_createa generic thread creation function; it can be used to point to any type of memory location. For a specific program that callspthread_create, the programmer knows the type of the argument passed to thevoid *parameter, so the programmer must recast it to its known type before dereferencing it. In this example, suppose that the address passed to theargsparameter contains the address of an integer variable:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26 /*
* an application-specific pthread main function
* must have this function prototype: int func_name(void *args)
*
* any given implementation knows what type is really passed in
* args: pointer to an int value
*/
int my_thr_main(void *args) {
int num;
// first recast args to an int *, then dereference to get int value
num = *((int *)args); // num gets 6
...
}
int main(void) {
int ret, x;
pthread_t tid;
x = 6;
// pass the address of int variable (x) to pthread_create's void * param
// (we recast &x as a (void *) to match the type of pthread_create's param)
ret = pthread_create(&tid, NULL,
my_thr_main, // a thread main function
(void *)(&x)); // &x will be passed to my_thr_main
// ...
译注 · 线程函数的原型写错了
上面代码注释中说线程主函数的原型必须是 int func_name(void *args),这是错的。pthread_create 要求的线程函数原型是 void *func_name(void *args)——返回 void *,而不是 int。按书中写法,现代编译器会直接报错:译者在 macOS 上用 gcc -Wall(Apple Clang)编译,得到 incompatible function pointer types passing 'int (void *)' 错误。第 14 章的 Pthreads 示例使用的是正确的 void * 返回类型。