简体   繁体   English

在生活游戏中使用calloc或malloc(在C语言中)

[英]Using calloc or malloc for Game of Life (in C)

I am using a text file where the user inputs parameters for Game of Life. 我正在使用一个文本文件,用户在其中输入生命游戏的参数。 In the first line I will ask the user to write two values, with the first value being the number of grid rows and the second value being the number of grid columns. 在第一行中,我将要求用户编写两个值,第一个值是网格行数,第二个值是网格列数。 The maximum grid can be 30 by 30. The second line will contain the initial occupied regions. 最大网格可以是30 x30。第二行将包含初始占用区域。 This can vary from 1 to 900 (all occupied). 范围从1到900(全部占用)。 For this reason I was planning to use malloc or calloc instead of a fixed element array. 因此,我计划使用malloc或calloc代替固定元素数组。 Which from these two is best for this scenario? 这两种方法中哪一种最适合这种情况?

malloc() followed by assignment of 0 to all bytes allocated is exactly like calloc() , except perhaps for (minor) performance. malloc()后跟分配的所有字节分配0方式与calloc()完全相同,除了(低级)性能。

In other words... doing calloc() and then using data in a text file to assign values to the allocated memory writes twice to that memory. 换句话说,...执行calloc() ,然后使用文本文件中的数据将值分配给已分配的内存,将对该内存写入两次。

Use malloc() unless you know the contents of the bytes will be 0 . 除非您知道字节的内容将为0否则请使用malloc()

Don't forget to use free() when you're done with the memory, whether you obtained it with malloc() or calloc() . 无论是通过malloc()还是calloc()获得内存,别忘了使用free() calloc()

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

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