0
 #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 不起作用?只是有点困惑。

4

3 回答 3

3

如果你有一个指向结构的指针,你应该使用->它来访问它的成员:

student->no = 306;

这是做的语法糖(*student).no = 306;。你的原因不起作用是因为operator priority。没有括号, 的.优先级高于*,并且您的代码等效于*(student.no) = 306;.

于 2013-02-08T21:15:30.847 回答
0

operator*具有非常低的优先级,因此您必须用括号控制评估:

(*student).no = 306;

虽然它总是可以这样做:

student->no = 306;

在我看来,这要容易得多。

于 2013-02-08T21:15:34.237 回答
0

你应该使用

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;
 }
于 2013-02-08T21:55:25.067 回答