Accessing a array of Structs using pointer notation
I am trying to learn C++ on my own and was trying out this. I have a struct one of whose member is an array of another structs. I have a question about alternative notation.
The structs that I have defined are
struct employeeRecordT {
string name;
string title;
string ssnum;
double salary;
int withholding;
};
struct payrollT {
int num;
employeeRecordT *array;
} payroll;
I am allotting memory to payroll using the following construct
payroll.array = new employeeRecordT[payroll.num];
where payroll.num is indicating the number of elements in the array. I can access the element name of the em开发者_运维百科ployeeRecordT by using the array notation e.g.
payroll.array[i].title
I wanted to know how to access this using the pointer notation, I have tried
payroll.(array+i)->name = "Vikas";
and I get the following error message from g++
toy.cc:30:13: error: expected unqualified-id before '(' token toy.cc:30:14: error: 'array' was not declared in this scope
I am trying to understand what I should be using and why? Could you guys help explain.
Thanks in advance.
Regards, Vikas
(payroll.array+i)->name = "Vikas";
array
is a member of payroll
, so when you were doing payroll.(array+i)
, the bracket notation (i.e. "do this first") was trying to use a variable array
, and not the one within the scope of payroll
.
Of course, using C++, the better solution is Neils. Use a std::vector instead of your own dynamically allocated storage if possible.
If it hurts, don't do it. Use a std::vector of your structures instead.
精彩评论