繁体   English   中英

用指向 C 中的结构的指针填充一个二维指针数组

[英]Fill a 2d array of pointers with pointers to structs in C

我有一个二维指针数组:

typedef struct Cell{
   Position p;
   unsigned int value;
} Cell;

typedef struct Position{
    unsigned int x;
    unsigned int y;
} Position;

int size = 4;
Cell ***cells = malloc(sizeof(Cell**) * size);
int i,j;
for(i = 0; i < size; i++){
    cells[i] = malloc(sizeof(Cell*) * size);
    for(j = 0; j < size; j++){
        cells[i][j] = malloc(sizeof(Cell));
    }
}

我现在要做的是用指向单元格的指针填充这个数组,并初始化这些单元格以包含值 0,如下所示:

for(i = 0; i < size; i++){
    for(j = 0; j < size; j++){
        Position p = {i,j};
        Cell c = {p, 0};
        cells[i][j] = &c; //This doesn't work
    }
}

正如您已经知道的那样,将 c 的地址写入指针 cells[i][j] 并不理想,因为现在每个指针都指向同一个地址。 但是我不知道如何用指向各个地址的指针填充这个数组。

我试过这样的事情:

cells[i][j]->value = 0;

这当然也行不通。 谁能给我一个关于如何解决我的问题的提示?

我不知道你为什么说cells[i][j]->value = 0; 不工作,我相信它应该。

这应该可以设置所有成员。

Cell ***cells = malloc(sizeof(Cell**) * size);
for(i = 0; i < size; i++){
    cells[i] = malloc(sizeof(Cell*) * size);
    for(j = 0; j < size; j++){
        cells[i][j] = malloc(sizeof(Cell));
        cells[i][j]->p.x = i;
        cells[i][j]->p.y = j;
        cells[i][j]->value = 0;
    }
}

您已经得到了答案,但我认为没有明显的理由进行如此多的分配,除非sizeof(Cell) * size * size大到足以使单个分配失败(但分配较小的部分不会)。 我建议只进行一次分配,这会带来一些好处。 没有特别的顺序:

  • 在大多数情况下更快的分配。
  • 更快地访问将被紧密打包的元素,因此对缓存更友好。
  • 更容易的 memory 管理 - 只有一个指针可以检查和free
  • 与为大量指针分配 memory 时相比,分配的总 memory 更少。
// one allocation:
Cell (*cells)[size][size] = malloc( sizeof *cells );

if(cells == NULL) exit(1); // check for allocation failure

for(int i = 0; i < size; i++){
    for(int j = 0; j < size; j++){
        (*cells)[i][j].p.y = i;
        (*cells)[i][j].p.x = j;
        (*cells)[i][j].value = 0;
    }
}

// ...

free(cells); // one deallocation

额外的:

for(i = 0; i < size; i++){
    for(j = 0; j < size; j++){
        Position p = {i,j};
        Cell c = {p, 0};
        cells[i][j] = &c; //This doesn't work
    }
    // to this line, 'c' & 'p' will be freed since it was allocated on stack not heap.
    // 'c' & 'p' will be freed when program gets out of 2nd for loop, so either you can
    // use memcpy to copy 'c' into cells[i][j] or use malloc to allocate 'c' and 'p'
}

暂无
暂无

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

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