如何更改结构指针的单个成员的值
How do you change the value of a single member of a struct pointer?
#include <iostream>
#include <cstring>
using namespace std;
struct Student {
int no;
char grade[14];
};
void set(struct Student* student);
void display(struct Student student);
int main( ) {
struct Student harry = {975, "ABC"};
set(&harry);
display(harry);
}
void set(struct Student* student){
struct Student jim = {306, "BBB"};
*student = jim; // this works
//*student.no = 306; // does not work
}
void display(struct Student student){
cout << "Grades for " << student.no;
cout << " : " << student.grade << endl;
}
如何使用指针仅更改结构的一个成员?为什么*student.no=306不起作用?只是有点困惑。
如果你有一个指向结构的指针,你应该使用->
来访问它的成员:
student->no = 306;
这是做(*student).no = 306;
的句法糖。您的操作失败的原因是运算符的优先级。如果没有括号,.
的优先级高于*
,并且您的代码等效于*(student.no) = 306;
。
operator*
的优先级非常低,因此必须使用括号控制评估
(*student).no = 306;
尽管它总是可以这样做:
student->no = 306;
在我看来这要容易得多。
您应该使用
student->no = 36
当我们在做这件事的时候,按值将结构传递给函数不是一个好的做法。
// Use typedef it saves you from writing struct everywhere.
typedef struct {
int no;
// use const char* insted of an array here.
const char* grade;
} Student;
void set(Student* student);
void display(Student* student);
int main( ) {
// Allocate dynmaic.
Student *harry = new Student;
harry->no = 957;
harry->grade = "ABC";
set(harry);
display(harry);
}
void set(Student *student){
student->no = 306;
}
void display(Student *student){
cout << "Grades for " << student->no;
cout << " : " << student->grade << endl;
delete student;
}
相关文章:
- 使用 back_inserter 从结构的单个成员创建向量
- 用于对项目进行分组并将单个项目映射到其他组成员的数据结构
- c++ 是否保证标头初始化的静态 const 成员跨编译单元和库共享单个实例?
- 是否值得使用位移在单个字节中存储多个小数据成员?
- 如何对具有相同类型的成员使用单个函数 C++.
- 如果类仅通过要求启用单个成员函数,仍然可以模棱两可地超载
- 将类成员数组组合到单个数组时性能下降
- 为类模板的单个成员定义专用化
- C++ 使用宏定义单个类的类成员
- 成员函数声明的参数列表后面的单个"与"是什么意思
- 为什么为结构的多个数据成员而不是单个成员添加填充
- 如何重载*op以乘以常量和单个dim数组成员
- 单个结构数据成员的奇怪指针地址
- PIMPL:导出具有单个STL成员的类(std::unique_ptr)
- 在单个(成员)函数的范围之外应用 RAII
- 具有单个成员的自定义结构(包装器)的集合(也是自定义结构)到单个成员的集合
- 如何将结构体数组的单个成员数组传递给函数以执行线性搜索
- 可以将基类的单个成员的状态更改为private吗?
- 单个成员而不是整个类的友元声明
- 如何更改结构指针的单个成员的值