views:

131

answers:

5
typedef struct {
    employeeT *employees;
    int nEmployees;
} *payrollT;

typedef struct {
    string name;
} *employeeT;

I need to do this without accessing it as an array:

employeeT e = payroll.employees[i];

but this gives me an error(expected identifier before '(' token) :

employeeT e = payroll.(*(employee+i));

before struct's I could interchange employees[i] and *(employee+i)

A: 

Well, you can do:

employeeT e = *(payroll.employees+i);

but what's wrong with the array syntax? It's certainly clearer.

Oli Charlesworth
A: 
employeeT e = *(payroll.employee+i);

should do the job.

ur
+3  A: 

Why do you need to avoid array syntax?

*(ptr+offset) == ptr[offset], strictly, every time.

You have NO performance penalty and the array syntax is clearer.


EDIT: I just got the real crux of the problem.

If payroll (in your example) is a pointer type, you need to use the arrow operator instead of the dot operator:

payroll->employees[0]
Platinum Azure
+1 for your finding of the `->` error. Perhaps you could just invert the two paragraphs of your answer, because the real answer is the second part ;-)
Jens Gustedt
@Jens Gustedt: Heh. I was thrown by the typedef into pointer type... that's something I never use and I think it's a terrible hack that should be outlawed from the standard. :-(
Platinum Azure
+1  A: 

As others noted,

employeeT e = *(payroll.employees + i);

(or *(payroll->employees + i) if payroll is a pointer instead of the struct itself) works just fine.

But let's go back to your question; why do you think that you can't access payroll.employees with the array syntax? The C standard is perfectly clear on the point that the two expressions are equivalent -- this is actually the definition of the array subscript operator [ ] (§6.5.2.1 Array Subscripting):

The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))). Because of the conversion rules that apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the initial element of an array object) and E2 is an integer, E1[E2] designates the E2-th element of E1 (counting from zero).

Stephen Canon
A: 

You have to recap the use of structs. Try *(payroll.employee+i).

Edit: Or you can use (*payroll).employee[i].

swegi
Or `payroll->employee[i]`.
Platinum Azure
@Platinum Azure: Yes, and in fact, I prefer the arrow notation for pointers, but I wanted to use the notation which seemed to be more familiar to the questioner.
swegi