B
Berk Birand
Hi all,
I have to use C-style structures for an assignement. I cannot have any
methods or constructors for it. What has surprised me is that in my
code, I have to allocate memory for an array of structures with malloc.
Otherwise, I get a seg fault. Here's the code:
struct Employee {
char* name; // Pointer to character string holding name of employee.
int salary;
};
// Allocate the employee array;
Employee* emp[20];
int ans; // return value of fscanf
int size = 0;
for (int i = 0; i < MAX_EMPS; i++)
{
//dynamically allocate memory
// otherwise seg fault
emp = static_cast <Employee*> (malloc (sizeof (Employee*)));
emp->name = static_cast <char*> (malloc (MAX_CHARS));
// Read one line of the file
ans = readEmployee(emp , inpfile);
if (ans == -1) {
break;
}
size++;
}
As you can see, I have to call malloc twice, cat the result. Is this
normal? Are there any other ways of avoiding this??
Thanks,
BB
I have to use C-style structures for an assignement. I cannot have any
methods or constructors for it. What has surprised me is that in my
code, I have to allocate memory for an array of structures with malloc.
Otherwise, I get a seg fault. Here's the code:
struct Employee {
char* name; // Pointer to character string holding name of employee.
int salary;
};
// Allocate the employee array;
Employee* emp[20];
int ans; // return value of fscanf
int size = 0;
for (int i = 0; i < MAX_EMPS; i++)
{
//dynamically allocate memory
// otherwise seg fault
emp = static_cast <Employee*> (malloc (sizeof (Employee*)));
emp->name = static_cast <char*> (malloc (MAX_CHARS));
// Read one line of the file
ans = readEmployee(emp , inpfile);
if (ans == -1) {
break;
}
size++;
}
As you can see, I have to call malloc twice, cat the result. Is this
normal? Are there any other ways of avoiding this??
Thanks,
BB