views:

115

answers:

5
#include <stdio.h>
#include <stdlib.h>

typedef int element;

struct cell {
    element e;
    struct cell *p;
};
typedef struct cell* CELL;

int main() {
    CELL* p;
    p = (CELL*) malloc (sizeof(struct cell));
    p->e = 8;       /* This ain't working */
    *p.e = 8;       /* This doesn't help anything either */

    return 0;
}

I'm just getting started with malloc and I just made a pointer to a newly created CELL, which is a struct. Now I'm trying to fill it with some values, but I'm greeted by an unfriendly "request for member e" in something not a structure or union". I did make a pointer to a struct that contains a member called e, or at least that's what I think I did. Why does this fail?

+6  A: 

Change

cel* p;
p = (CELL*) malloc (sizeof(struct cell));

*p.e = 8;

to

struct cell* p; // or CELL p;
p = (CELL) malloc (sizeof(struct cell));

(*p).e = 8; // . has higher precedence than *
codaddict
+3  A: 

Since the typedef is a pointer type I think you want to cast it as a CELL not a CELL*.

Myles
+9  A: 

I think this nicely illustrates a rule of good C style - do not create typedefs that hide the fact that something is a pointer.

anon
A: 

I settled for this:

#include <stdio.h>
#include <stdlib.h>

typedef int element;

struct cell {
    element e;
    struct cell *p;
};
typedef struct cell* CELL;

int main() {
    CELL p;
    p = (CELL) malloc (sizeof(struct cell));
    p->e = 8;
    (*p).e = 8;

    return 0;
}

Thanks everyone.

Pieter
+1  A: 

Just to complete the other fine answers by being explicit:

in your code, you define the CELL type to be "a pointer to a struct cell". Then you create yo local variable p to be a CELL *, i.e. "a pointer to a value of type CELL". In other words, a pointer to a pointer. That's one level too much. The "->" operator only follows one level of indirection, not two.

Thomas Pornin