我一直对此很感兴趣,当在数组内使用结构体时,就内存分配而言,是为每个条目分配一个新的结构体更好,还是为 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 调用,但也可能存在只能使用第一种方法的情况。
对此有什么见解吗?
谢谢!