【问题标题】:How to Access each element of a Structure with Pointer in C++如何在 C++ 中使用指针访问结构的每个元素
【发布时间】:2012-01-19 01:06:00
【问题描述】:

我在访问单个结构元素时遇到问题。如何使用指针输出每个结构元素?

#include <iostream>

using namespace std;

struct student{
int rollno;
float marks;
char name[45];
};

int main(){
student s1[2]={{1,50.23,"abc"},{2,65.54,"def"}};


for(int j=0;j<2;j++){
    cout<<"Output Rollno, Marks and Name Using Pointer"
}
return 0;
}

【问题讨论】:

    标签: c++ pointers structure


    【解决方案1】:

    只需将地址分配给一个指针,然后打印它。

    student *ptr=s1; // or &s1[0], instead.
    cout<<ptr->rollno;
    

    【讨论】:

    • 谢谢...一个普遍的问题,如何在stackoverflow评论中打印代码??
    • 用“`”(数字左边的键,字母上方)包装它
    【解决方案2】:

    你没有指针。

    要输出字段,您可以执行在任何其他情况下会执行的操作,例如:

    cout << "marks = " << s1[j] << "\n";
    

    【讨论】:

    • 你可以显示语法,将 s[] 视为指针。例如:'cout
    【解决方案3】:

    你的循环应该是这样的:

    for(int j=0;j<2;j++){
        cout<<"Rollno:" << s1[j].rollno << " Marks:" << s1[j].marks << " Name:" << s1[j].name << endl;
    }
    

    或者,使用指针(即数组+偏移量):

    for(int j=0;j<2;j++){
        cout<<"Rollno:" << (s1+j)->rollno << " Marks:" << (s1+j)->marks << " Name:" << (s1+j)->name << endl;
    }
    

    【讨论】:

      【解决方案4】:

      如果你想成为真正的原始人:

      void* ptr = &s1[0];
      
      for(int j=0;j<2;j++){
          cout<< (int)*ptr << "," << (float)*(ptr+sizeof(int)) << "," << (char*)*(ptr+sizeof(int)+sizeof(float)) << endl;
      }
      

      【讨论】:

        【解决方案5】:
        char* p = (char* )s1;
        
        for(int j=0;j<2;j++){ 
            int* a = (int*) p;
            cout << *a  << " ";
            a++;
            float* b = (float*) a;
            cout << *b  << " ";
            b++;
            char* c = (char*) b;
            cout << c << " ";
            c = c + 45 + strlen(c);
            cout<<endl;
            p = c;
        } 
        

        【讨论】:

          猜你喜欢
          • 2023-02-16
          • 2011-06-04
          • 2017-01-24
          • 2020-11-05
          • 1970-01-01
          • 2017-01-04
          • 2014-02-19
          • 1970-01-01
          • 2013-06-11
          相关资源
          最近更新 更多