Allocating memory for a Structure in C

后端 未结 7 1483
清酒与你
清酒与你 2020-12-12 17:10

I\'m tasked to create a program which dynamically allocates memory for a structure. normally we would use

x=malloc(sizeof(int)*y);

However,

相关标签:
7条回答
  • 2020-12-12 17:47

    struct st *x = (struct st *)malloc(sizeof(struct st));

    0 讨论(0)
  • 2020-12-12 17:51

    My favorite:

    #include <stdlib.h>
    
    struct st *x = malloc(sizeof *x); 
    

    Note that:

    • x must be a pointer
    • no cast is required
    • include appropriate header
    0 讨论(0)
  • 2020-12-12 17:54

    struct st* x = malloc( sizeof( struct st ));

    0 讨论(0)
  • 2020-12-12 17:58

    It's exactly possible to do that - and is the correct way

    Assuming you meant to type

    struct st *x = malloc(sizeof(struct st)); 
    

    ps. You have to do sizeof(struct) even when you know the size of all the contents because the compiler may pad out the struct so that memebers are aligned.

    struct tm {
      int x;
      char y;
    }
    

    might have a different size to

    struct tm {
      char y;
      int x;
    }
    
    0 讨论(0)
  • 2020-12-12 18:01

    This should do:

    struct st *x = malloc(sizeof *x); 
    
    0 讨论(0)
  • 2020-12-12 18:06

    You're not quite doing that right. struct st x is a structure, not a pointer. It's fine if you want to allocate one on the stack. For allocating on the heap, struct st * x = malloc(sizeof(struct st));.

    0 讨论(0)
提交回复
热议问题