简体   繁体   English

calloc,malloc和动态结构分配

[英]calloc, malloc and dynamic struct allocation

I am trying to dynamically allocate an array of structures in c so that I can refer to them the same as if I had done a static declaration. 我正在尝试在c中动态分配结构数组,以便可以像执行静态声明一样引用它们。 I understand that calloc() does the additional step of initializing all the allocated memory to 0. But, other than that, are the 2 completely interchangeable for the following code? 我知道calloc()会执行将所有分配的内存初始化为0的附加步骤。但是,除此之外,以下代码2是否可以完全互换? If I am using fread() and fwrite() to get these data structures in and out of a file, does calloc() help or hinder this? 如果我使用fread()和fwrite()将这些数据结构移入和移出文件,calloc()会有所帮助还是阻碍呢?

#define MAGIC   13
    struct s_myStruct {
int a[6000][400];
int b[6000][400];
int c[6000][400];
};

struct s_myStruct stuff[MAGIC];
vs
struct s_myStruct *stuff = calloc(MAGIC, sizeof(s_myStruct);

Thank you. 谢谢。

They're not the same. 他们不一样。 Declaring the data like this: 像这样声明数据:

struct s_myStruct stuff[MAGIC];

will leave the memory uninitialized if you're declaring it in function scope (which you must be, given the second choice). 如果在函数范围内声明内存,则将使内存保持未初始化状态(必须选择第二个选项)。 Adding = {0} before the semicolon rectifies this. 在分号之前加上= {0}可纠正此问题。

The second choice, of using calloc, allocates the memory on the heap. 第二种选择是使用calloc,在堆上分配内存。

There's always a difference though: sizeof(stuff) will be 13 * sizeof(struct s_myStruct) in the first case, and the size of a pointer in the second case. 但是总会有一个区别:在第一种情况下, sizeof(stuff)为13 * sizeof(struct s_myStruct),在第二种情况下为指针的大小。

You really don't want to do the first one, as you'd be putting 13 * 3 * 6000 * 400 * 4 = 370MB on the stack. 您真的不想做第一个,因为您要在堆栈上放入13 * 3 * 6000 * 400 * 4 = 370MB。

But this has nothing to do with using fread and fwrite . 但这与使用freadfwrite

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM