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

时间:2013-02-08 21:14:10

标签: c++

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

3 个答案:

答案 0 :(得分:3)

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

student->no = 306;

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

答案 1 :(得分:0)

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

(*student).no = 306;

虽然它总是可以这样做:

student->no = 306;

在我看来更容易。

答案 2 :(得分: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;
 }