Allocating memory for a Structure in C

匿名 (未验证) 提交于 2019-12-03 01:58:03

问题:

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

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

However, what do I use for a structure variable? I don't think its possible to do

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

Could someone help me out? Thanks!

回答1:

My favorite:

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

Note that:

  • x must be a pointer
  • no cast is required
  • include appropriate header


回答2:

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));.



回答3:

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



回答4:

This should do:

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


回答5:

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



回答6:

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; } 


回答7:

I believe, when you call sizeof on a struct type, C recursively calls sizeof on the fields of the struct. So, struct st *x = malloc(sizeof(struct st)); only really works if struct st has a fixed size. This is only significant if you have something like a variable sized string in your struct and you DON'T want to give it the max length each time.

In general,

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

works. Occasionally, you will run into either variable sized structs or 'abstract' structs (think: abstract class from Java) and the compiler will tell you that it cannot determine the size of struct st. In these cases, Either you will have to calculate the size by hand and call malloc with a number, or you will find a function which returns a fully implemented and malloc'd version of the struct that you want.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!