普通变量 的 作用 : 将 普通变量 传入函数作为参数 ,
一级指针 的 作用 : 将 普通变量 的 一级指针 传入函数作为参数 ,
二级指针 的 作用 : 将 普通变量 的 二级指针 传入函数作为参数 ,
使用 二级指针 作为参数 , 可以实现如下功能 :
void createArray(int **arr, int size) {
*arr = malloc(size * sizeof(int));
}
void changePointer(int **ptr) {
int new_value = 10;
*ptr = &new_value; // 修改指针值
}
void process2DArray(int **array, int rows, int cols) {
//...
}
Student 是一个结构体 , C++ 中 结构体 可以当做 类 使用 ;
在 int getStudent(Student** stu) 函数中 , 传入 Student 类的二级指针 , 并在堆内存中创建一个 Student 类 , 赋值给一个临时的一级指针 Student* tmp ;
为 tmp 一级指针 指向的 内存空间 设置一个默认数据 , 作为参考 , 这里将 age 成员设置为 18 ;
将 tmp 一级指针 赋值给 参数中的 Student** stu 二级指针 指向的 内存中 , 即 将 该 二级指针 指向 tmp 一级指针 ;
上述操作 在 函数中 , 修改了 二级指针 指向 的一级指针 的值 , 也就是 修改了 一级指针 的地址 , 一级指针 的内存位置 与原来的 一级指针 内存位置 不同 ;
代码示例 :
// 导入标准 io 流头文件 其中定义了 std 命名空间
#include
// 导入 std 命名空间
using namespace std;
struct Student
{
char name[64];
int age;
};
int getStudent(Student** stu)
{
if (stu == NULL)
{
// 传入的参数不合法, 返回错误码 1
return 1;
}
// 声明 Student 类对象
Student* tmp = NULL;
// 为声明的 Student 类对象分配内存
tmp = (Student*)malloc(sizeof(Student));
if (tmp == NULL)
{
// 分配内存失败 , 返回错误码 2
return 2;
}
// 设置结构体成员值
tmp->age = 18;
// 将 在 堆内存 中 ,
// 创建的 Student 类对象设置给
// 对应的 二级指针 指向的 一级指针 地址
*stu = tmp;
// 执行成功
return 0;
}
int main() {
// 声明 Student 对象
Student* stu = NULL;
// 调用函数 将二级指针传入函数
// 在函数内部创建 Student 对象
getStudent(&stu);
// 打印结构体成员
printf("stu->age = %d\n", stu->age);
// 控制台暂停
system("pause");
return 0;
}
执行结果 :
stu->age = 18
请按任意键继续. . .
