如何更改结构指针的单个成员的值

How do you change the value of a single member of a struct pointer?

本文关键字:单个 成员 指针 何更改 结构      更新时间:2023-10-16
 #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;
 }