Why do I have to use malloc when I have a pointer to a struct?

后端 未结 5 419
眼角桃花
眼角桃花 2021-01-23 10:55
 struct element {
     int val;
     int z;
 };
 typedef struct element ELEM;

Look at this example:

 int main()
 {

    ELEM z;
    z =         


        
5条回答
  •  无人及你
    2021-01-23 11:49

    You only need to use malloc if you intend to dynamically allocate memory. Otherwise, your pointer must point to something. If you intend to use your pointer when it doesn't point to valid memory, it is undefined behavior.

    struct Elem
    {
        int val;
    };
    
    int main() {
        struct Elem elem;
        struct Elem* ptr; // can't use pointer, points to nothing
        ptr = &elem; // good, points to elem
        ptr->val = 5;
        printf("%d", ptr->val);
        ptr = malloc(sizeof(struct Elem)); // good, points to object on the heap
        ptr->val = 10;
        printf("%d", ptr->val);
        free(ptr);
        return 0;
    }
    

提交回复
热议问题