Why can't I access this struct through its pointer?
#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 struc开发者_如何学运维t
. 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?
I think this nicely illustrates a rule of good C style - do not create typedefs that hide the fact that something is a pointer.
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 *
Since the typedef is a pointer type I think you want to cast it as a CELL not a CELL*.
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.
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.
精彩评论