2

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

5 Answers 5

3

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

student *ptr=s1; // or &s1[0], instead.
cout<<ptr->rollno;
Sign up to request clarification or add additional context in comments.

2 Comments

thanks... one general question, How to print Code in stackoverflow Comment??
wrap it in "`" (the key in the left of the numbers, above the letters)
2

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

1 Comment

Can u show the Syntax, treating s[] as pointer. eg: 'cout<<*(s1+j)'
2

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

Comments

2

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.