C language structure pointer traps

. "" I, and "->" differences:

When declaring a structure, since the automatically allocated memory structure, it is possible to directly access the corresponding memory cell structures in the body, for example. "":

typedef struct Node{
    int value;
}node;

node o;
o.value=2;

But if the statement is a pointer to a structure, it is necessary to manually open a structure of the memory, after the pointer to the memory block, then use the "->" internal variable access, while (* o) .value equivalent to o-> value.

node *o;
o->value=2;

Second, the pointer points to the structure must be initialized:

#include <stdio.h>

typedef struct Node{
    int value;
}node;

int main(){
    node *o;
    o->value=2;
    printf("%d",o->value);

    return0;
}

This code compiler no problem running it wrong, why?
       Defines a structure pointer o used to point to a node structure, but you did not give him an assignment, the system only knows "o should be the first address of a node structure of the memory unit," but the address is how much, not yet assigned , so in this case o value of NULL, * o point is a random or empty memory space, often say "wild pointer." Therefore p-> a = 1 sentence error occurs. So we should be initialized to o, initialized in two ways.
       One is dynamically allocated memory malloc:

o=(node *)malloc(sizeof(node));
o->value=2;

O Another point is a node existing structure:

node r;
o = &r;
o->value=2;//因为o为指针,所以此时其实为r的value被赋值为2

 

Released four original articles · won praise 0 · Views 62

Guess you like

Origin blog.csdn.net/qq_40285768/article/details/104607834