结构体变量 作为函数形参 , 在函数中 , 只能访问 该函数形参 , 无法修改 结构体内存 的值 ;
结构体变量 通过 形参形式传入 , 会在该 printf_student
方法的栈内存中 , 重新为该 结构体变量 分配内存 , 函数执行结束 , 这块内存就自动收回了 ;
因此在该函数中 , 结构体形参 , 只能访问 , 不能修改 ;
代码示例 :
/**
* @brief printf_student 结构体变量 作为参数
* @param s
*/
void printf_student(Student s)
{
printf("printf_student : name = %s, age = %d, id = %d\n", s.name, s.age, s.id);
}
结构体指针变量作为参数 , 可以 通过 指针 间接赋值 ,
在该函数中 , 将 from 结构体指针指向的变量 拷贝到 to 结构体指针指向的变量 ;
注意 : 函数中传入的是 指向 结构体变量的指针 , 不能直接传入结构体变量 , 如果直接传入结构体变量 , 该结构体变量直接在本函数中的栈内存中起作用 , 函数执行完毕后 , 栈内存的结构体变量 直接回收 ;
代码示例 :
/**
* @brief copy_student 结构体指针变量作为参数 .
* 将 from 结构体变量拷贝到 to 结构体变量中
* 注意 : 函数中传入的是 指向 结构体变量的指针 , 不能直接传入结构体变量
* 如果直接传入结构体变量 , 该结构体变量直接在本函数中的栈内存中起作用
* 函数执行完毕后 , 栈内存的结构体变量 直接回收 ;
* @param to
* @param from
*/
void copy_student(Student *to, Student *from)
{
// 将 from 指针指向的结构体变量 赋值给
// to 指针 指向的结构变量
*to = *from;
}
完整代码示例 :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/**
* @brief The Student struct
* 定义 结构体 数据类型 , 同时为该结构体类型声明 别名
* 可以直接使用 别名 结构体变量名 声明结构体类型变量
* 不需要在前面添加 struct 关键字
*/
typedef struct Student
{
char name[5];
int age;
int id;
}Student;
/**
* @brief copy_student 结构体指针变量作为参数 .
* 将 from 结构体变量拷贝到 to 结构体变量中
* 注意 : 函数中传入的是 指向 结构体变量的指针 , 不能直接传入结构体变量
* 如果直接传入结构体变量 , 该结构体变量直接在本函数中的栈内存中起作用
* 函数执行完毕后 , 栈内存的结构体变量 直接回收 ;
* @param to
* @param from
*/
void copy_student(Student *to, Student *from)
{
// 将 from 指针指向的结构体变量 赋值给
// to 指针 指向的结构变量
*to = *from;
}
/**
* @brief printf_student 结构体变量 作为参数
* @param s
*/
void printf_student(Student s)
{
printf("printf_student : name = %s, age = %d, id = %d\n", s.name, s.age, s.id);
}
/**
* @brief main
* @return
*/
int main()
{
// 声明结构体变量 , 同时进行初始化操作
Student s1 = {"Tom", 18, 1};
// 声明结构体变量 , 不进行初始化
Student s2;
// 将结构体变量 s1 赋值给 结构体变量 s2
s2 = s1;
// 打印 s2 结构体的值
printf("s2 : name = %s, age = %d, id = %d\n", s2.name, s2.age, s2.id);
// 打印两个结构体变量的地址值 , 上述赋值不是地址赋值 , 而是实际的值之间进行的赋值
printf("s1 address = %d, s2 address = %d\n", &s1, &s2);
// 由上面的 s2 打印结果可知 , 将 s1 结构体变量赋值给 s2 结构体变量
// 会为 s2 的每个 结构体成员 进行赋值
// 将 s1 结构体的 成员 取出 并赋值给 s2 结构体 的 相应成员
// 声明结构体变量 , 不进行初始化
Student s3;
// 将 s1 结构体变量 赋值给 s3 结构体变量
copy_student(&s3, &s1);
// 打印 s3 结构体的值
printf_student(s3);
// 命令行不要退出
system("pause");
return 0;
}
执行结果 :