3

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

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Tried what you were recommending and it works. I should have thought of that. In hindsight, it appears obvious. I agree with both Neil and you that I should be using vector (and in general use STL wherever possible). I was doing this just for learning.
5

If it hurts, don't do it. Use a std::vector of your structures instead.

1 Comment

-1: When people bring up a really broken question which shows that they've jumped into the implementation before thinking about the design, it's all fine and well to give high-level advice. But to be fair, this was a precise and specific question with a simple direct answer, no need to sandbag the guy for asking.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.