0
int noOfEmployee = 0;
cout << "Enter no. of Employee" << endl;
cin >> noOfEmployee;

Ereg = new EMPLOYEE[noOfEmployee];

string defaultName = "Emloyee";

for(int i = 0; i < noOfEmployee; i++) {
    Ereg->regno = i + 1;
    Ereg->name = defaultName;
}

for(int i = 0; i < noOfEmployee; i++) {
    cout << Ereg->regno << "\t"
         << Ereg->name << endl;
}

delete [] Ereg; //segmentation Fault if [] missed

output is:

Enter no. of employee
5
5    Employee
5    Employee
5    Employee
5    Employee

How could access array elements in this or do something like this

Ereg[i]->regno = i;
Ereg[i]->name = defaultName;
0

4 Answers 4

1

Your output repeats itself because you never use Ereg as an array, only as a pointer to EMPLOYEE.

How could access array elememts in this or do something like this

Ereg[i]->regno = i;
Ereg[i]->name = defaultName;

Use . instead of ->, because Ereg[i] is a struct, not a pointer to struct.

//segmentation Fault if [] missed

This is expected. You need [] because you allocated an array. Hence, delete[] must be used to avoid undefined behavior.

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

Comments

1

Ereg points to the 1st element of array, so Ereg->regno or Ereg->name will always access the 1st element.

How could access array elements

You should

for(int i = 0; i < noOfEmployee; i++) {
    Ereg[i].regno = i + 1;
    Ereg[i].name = defaultName;
}

for(int i = 0; i < noOfEmployee; i++) {
    cout << Ereg[i].regno << "\t"
         << Ereg[i].name << endl;
}

See subscript operator.

BTW

//segmentation Fault if [] missed

You should use delete[] for array new[]d (and use delete for pointer newd).

Comments

0

Thanks for help,

There is one way of doing this i got just now.

As incrementing a structure pointer will move it towards next structure location so I used basic method.

(Ereg + i)->regno = i;
(Ereg + i)->name = defaultname;

And it worked just fine.

Comments

0

This is some kind of fun....

Also I can do this to use as a array.

As we know

*(Ereg + i) = Ereg[i]
// this is how array works, so I can write this

(Ereg + i) as (&Erg[i])

And this also worked fine.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.