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

后端 未结 5 422
眼角桃花
眼角桃花 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:52

    In your first example,

    int main() {
      ELEM z;
      z =  6;
      printf("%d",z);
    }
    

    You are creating a z Elem on the stack. This is a very efficient operation, and the language will manage the memory allocated to z for you - that is when z goes out of scope it will automatically be freed. In contrast, your second example,

    ELEM *z;
    

    Creates a pointer on the stack (which is a 32-bit value on a 32-bit OS, and a 64-bit value on a 64-bit OS) but does not allocate any elements. That is the purpose of the malloc routine, to allocate memory on the heap. You may point to one (as in your example), or many different elements dynamically through your pointer into the heap and you must free memory you allocate.

提交回复
热议问题