当前位置: 动力学知识库 > 问答 > 编程问答 >

How to Access each element of a Structure with Pointer in C++

问题描述:

I am having problems with accessing individual structure elemnsts. How to output each structure element using pointer?

#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;

}

网友答案:

Just assign the address to a pointer, and print it.

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

You don't have a pointer.

To output the fields, you do what you'd do in any other situation, e.g.:

cout << "marks = " << s1[j] << "\n";
网友答案:

your loop should be something like:

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

or, using pointer (i.e. array + offset):

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

If you wanted to be real raw:

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;
}
网友答案:
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;
} 
分享给朋友:
您可能感兴趣的文章:
随机阅读: