【发布时间】:2012-02-25 15:13:49
【问题描述】:
我一直对此感到好奇,当在数组内部使用结构时,就内存分配而言,是为数组中的每个条目分配一个新结构更好,还是更好在数组中为 N 个结构分配足够的空间。
//pointer based:
struct myStructure ** tmp = malloc(sizeof(struct myStructure *) * N);
tmp[0] = malloc(sizeof(struct myStructure));
tmp[0]->whatever = true;
//or structure in the array:
struct myStructure * tmp = malloc(sizeof(struct myStructure) * N);
tmp[0].whatever = true
其中有什么好处?我觉得使用第二种形式是更好的做法,因为您最终会得到更少的小型 malloc 调用,但在某些情况下您可能只能使用第一种方法。
对此有何见解?
谢谢!
【问题讨论】: