我在访问个别结构元素时遇到问题。如何使用指针输出每个结构元素?
#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;
}
答案 0 :(得分:3)
只需将地址指定给指针,然后打印即可。
student *ptr=s1; // or &s1[0], instead.
cout<<ptr->rollno;
答案 1 :(得分:2)
你没有指针。
要输出字段,您可以在其他任何情况下执行操作,例如:
cout << "marks = " << s1[j] << "\n";
答案 2 :(得分:2)
你的循环应该是这样的:
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;
}
答案 3 :(得分:2)
如果你想成为真正的原始人:
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;
}
答案 4 :(得分:0)
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;
}