[英]Dynamically allocating 2-dimensional array in Struct (in C)
我有一个名为container的结构,它有两个字段: labels和linked_to_containers ; 字段标签被设计为int的2维数组,而字段linked_to_containers被设计为int指针的2维数组。 除此之外,我还有一个在启动程序中动态创建的struct container
数组。 我写下了下面的代码,但有一点我不确定是我在函数container_init()
使用的第一个malloc
。 由于struct container
仍然没有初始化它的大小,这是使用malloc
创建struct容器数组的正确方法吗?
请在我的代码注释中查看我的问题,我将非常感谢您的反馈。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct container {
int *labels[2]; /* two-dimensional array of int */
int **linked_to_container[2]; /* two-dimensional array of pointers to label */
} container;
int get_next_container_index(int current_container_index, int max_index)
{
if (max_index - current_container_index >= 1)
{
return current_container_index + 1;
}
else
return 0; /* elements at two ends are linked */
}
container *allcontainers; /* an array for all containers */
void container_init(int num_containers, int column_num)
{
/* is this right to malloc memory on the array of container when the struct size is still unknown?*/
allcontainers = (container *) malloc(num_containers * sizeof(container));
int i;
for (i = 0; i < num_containers; i++)
{
container *current_container = &allcontainers[i];
current_container->labels[0] = malloc(column_num * sizeof(int));
current_container->labels[1] = malloc(column_num * sizeof(int));
current_container->linked_to_container[0] = malloc(column_num * sizeof(int *));
current_container->linked_to_container[1] = malloc(column_num * sizeof(int *));
int j;
for (j = 0; j < column_num; j++)
{
current_container->labels[0][j] = 0; /* initialize all labels to 0 */
current_container->labels[1][j] = 0;
int next_container = get_next_container_index(i, num_containers - 1); /* max index in all_containers[] is num_containers-1 */
current_container->linked_to_container[0][j] = &(allcontainers[next_container]->labels[0]);
}
}
对我来说这条线似乎完全没问题,因为它的定义, struct container
的大小是众所周知的。 唯一未知的大小是结构中指针最终指向的数组的大小,但这不会影响指针本身的大小,因此也不会影响结构的大小。
我看到的唯一问题是:
current_container->linked_to_container[0][j] = &(allcontainers[next_container]->labels[0]);
linked_to_container[0][j]
的类型为int*
,但labels[0]
的类型为int*
,因此&(labels[0])
的类型为int**
。 我不知道你在这里试着完成的任务,但你可能需要另一个索引labels[0][...]
或&
应不应该存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.