Panda
Panda

Reputation: 2520

Play with elements of Array of Structures in C++

I have just started learning c++ and I am stuck over here. I made a structure

...
struct student{
string name;
int roll;
};
...

And then, I called it globally. student s1[20]; Inside my main function, I did something like this

...
int count=0;
student *p;
p=s1;
cout<<"Enter the Number of records, you wish to consider.";
cin>>arraySize;
p = new student[arraySize];
while (count!=arraySize) {
    cout<<"Enter name.";
    cin>>*(p+count)->name; //Error comes over here
}
...

The error message, I get is Indirection requires pointer operand. Can some one Please help me out with this ??

Upvotes: 1

Views: 45

Answers (2)

Cory Kramer
Cory Kramer

Reputation: 117926

You could either use pointer arithmetic as you are doing

(p+count)->name

or more canonically use [] to index into the array

p[count].name

The reason you are getting an error is because you are combining * which dereferences your pointer with -> which also dereferences your pointer. You could just do one or the other

(p+count)->name
(*(p+count)).name

Though as I said for readability I would prefer using index notation []

Upvotes: 5

anukul
anukul

Reputation: 1962

Using *(p+count)->name makes no sense.

Picking up from here, foo->bar calls method bar on the object pointed by pointer foo.

So, you should either do (p+count)->name or (*(p+count)).name.

Note the brackets, they're necessary as . has greater precedence than *.

Upvotes: 2

Related Questions