struct node
{
int data;
node* pointerToNextNode;
};
Here pointerToNextNode
is the type of struct node
, and it is declared inside the struct. How does the struct know the type of next pointer of its own type - when it itself hasn't been formed yet?
There is no keyword extern
used. How does this work?
It doesn't need to know the structure, it's enough to know the type name, namely struct node
— and that has already been defined.
Same result you can obtain by forward type declaration:
struct node; // declare the struct not defining it
struct node *pointer; // declare variable
void foo()
{
if(pointer != NULL) // OK, we use the pointer only
if(pointer->x == 0) // invalid use - struct contents unknown yet
return;
}
struct node { // supply a definition
int x;
};
void bar()
{
if(pointer != NULL)
if(pointer->x == 0) // OK - struct contents already known
return;
}
Here
pointerToNextNode
is the type ofstruct node
No, it's not. It's of type struct node *
struct node* pointerToNextNode;
allocates memory for a pointer variable of type struct node
.
It does not allocate memory for struct node
, so, till point, it does not need to know about the size and representation of struct node
. Only the (data)type name is sufficient.
Also, it's worthy to mention, without a typedef
in place, node* pointerToNextNode;
should not be valid. It should be written like below
typedef struct node node;
struct node
{
int data;
node* pointerToNextNode;
};
BTW, private:
is not C
thing, if i'm not wrong.
for me this doesn't compile using CC -- and exactly because of what you said. you would have to use struct node *
to make the compiler aware you want memory for a pointer
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.