c语言程序入门5 指针












什么时候用空指针,指针定义的时候











#include <stdio.h>
// 定义返回 char 类型,接受 int 和 float 参数的函数指针类型
typedef char (*func_ptr)(int, float);
// 定义一个符合要求的函数
char my_function(int a, float b) {
printf("Received int: %d and float: %.2f\n", a, b);
return 'A'; // 返回一个字符
}
int main() {
// 声明一个函数指针并将其指向 my_function
func_ptr ptr = my_function;
// 通过函数指针调用函数
char result = ptr(10, 3.14);
printf("Returned character: %c\n", result);
return 0;
}


#include <stdio.h>
// 定义一个返回 void,参数为 void* 类型的函数指针类型
typedef void (*func_ptr)(void*);
// 定义一个符合要求的函数,接受一个 void* 类型的参数
void my_function(void* ptr) {
int* int_ptr = (int*)ptr; // 将 void* 转换为 int* 类型
printf("The value is: %d\n", *int_ptr);
}
int main() {
int value = 42;
// 声明一个函数指针并将其指向 my_function
func_ptr ptr = my_function;
// 通过函数指针调用函数
ptr(&value); // 传递一个 int 类型的指针作为 void* 参数
return 0;
}
---
### 代码解释
#### 1. 定义函数指针类型
```c
typedef void (*func_ptr)(void*);
```
- **功能**:定义了一个名为 `func_ptr` 的函数指针类型。
- **说明**:`func_ptr` 是一个指向函数的指针,该函数的返回类型为 `void`,参数为 `void*` 类型。
#### 2. 定义函数
```c
void my_function(void* ptr) {
int* int_ptr = (int*)ptr; // 将 void* 转换为 int* 类型
printf("The value is: %d\n", *int_ptr);
}
```
- **功能**:定义了一个符合 `func_ptr` 类型的函数 `my_function`。
- 接受一个 `void*` 类型的参数 `ptr`。
- 在函数内部,将 `void*` 类型的指针转换为 `int*` 类型的指针。
- 通过解引用 `int*` 类型的指针,访问并打印指向的 `int` 类型的值。
#### 3. 主函数
```c
int main() {
int value = 42;
// 声明一个函数指针并将其指向 my_function
func_ptr ptr = my_function;
// 通过函数指针调用函数
ptr(&value); // 传递一个 int 类型的指针作为 void* 参数
}
```
- **功能**:
- 定义了一个 `int` 类型的变量 `value`,并初始化为 `42`。
- 声明了一个 `func_ptr` 类型的函数指针 `ptr`,并将其指向 `my_function`。
- 通过函数指针 `ptr` 调用 `my_function`,并传递 `value` 的地址作为参数。
### 输出
运行程序后,输出结果为:
```
The value is: 42
```
### 关键点
1. **函数指针类型定义**
- `typedef void (*func_ptr)(void*);` 定义了一个函数指针类型 `func_ptr`,它指向的函数返回类型为 `void`,参数为 `void*` 类型。
- 这种定义方式使得函数指针可以指向任何符合这种签名的函数。
2. **函数参数类型转换**
- 在 `my_function` 中,`void*` 类型的参数 `ptr` 被显式转换为 `int*` 类型的指针:
```c
int* int_ptr = (int*)ptr;
```
- 这种转换是必要的,因为 `void*` 类型的指针不能直接解引用,必须转换为具体的类型指针。
3. **函数指针的使用**
- 在 `main` 函数中,声明了一个 `func_ptr` 类型的函数指针 `ptr`,并将其指向 `my_function`。
- 通过函数指针 `ptr` 调用函数时,传递的参数是 `int` 类型的指针,但函数内部将其视为 `void*` 类型的参数。
4. **类型安全**
- 虽然函数指针的参数类型是 `void*`,但函数内部明确要求这个指针必须指向 `int` 类型的数据。如果传递的指针指向其他类型的数据,可能会导致未定义行为。
### 注意事项
1. **类型匹配**
- 调用函数时,必须确保传递的指针指向 `int` 类型的数据。如果传递了其他类型的指针,可能会导致运行时错误。
2. **文档说明**
- 在函数的文档中明确说明参数必须指向 `int` 类型的数据,以避免误用。
3. **通用性与安全性**
- 使用 `void*` 类型的参数可以增加函数的通用性,但同时也需要在函数内部进行严格的类型检查和转换,以确保操作的安全性。
浙公网安备 33010602011771号