1

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 ??

Panda
  • 2,400
  • 3
  • 25
  • 35
  • cin>>*(p+count)->name; change to this cin >> (p + count)->name; *(p + count)->name; resultin in dereference a var that not an address and cause error, you just want to fill the var, so just do it directly. – AchmadJP Feb 12 '16 at 13:09

2 Answers2

5

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 []

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
2

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 *.

Community
  • 1
  • 1
anukul
  • 1,922
  • 1
  • 19
  • 37