【发布时间】:2011-12-06 04:02:14
【问题描述】:
我正在尝试使用 malloc 为几个结构分配内存。我已经完成了研究,但找不到任何对我有帮助的东西。以下是结构:
typedef struct _square
{
char figure;
int num_neighbors;
struct _square *neighbors[7];
} point;
typedef struct_plot
{
int num_squares;
struct _square *dots;
} plot;
指针 *dots 应指向正方形指针数组 (*neighbors[7]) 的第一个元素,num_squares 的值是函数的输入。
有人有什么想法吗?
编辑: 这是我一直在尝试的:
plot* plot_create(int size)
{
plot *newPlot;
square * square_neighbors[8];
if((newPlot = (plot *)malloc(sizeof(plot))) == NULL)
{
printf("Allocation error");
return NULL;
}
if((square_neighbors = (node *)malloc(size*sizeof(square))) == NULL)
{
printf("Allocation error 2");
return NULL;
}
return newPlot;
}
【问题讨论】:
-
到目前为止你尝试过什么?您具体遇到了什么问题?
-
请发表您的尝试以及您认为错误的地方。
-
注意:你在 typedef struct_plot 中有错字 - 它应该是 typedef struct _plot。
-
为什么一个正方形只有 7 个邻居?通常,人们会假设 8 或 4(取决于对角线是否计算在内)。
-
@Jonathan OP 也使用
square_neighbors[8]。在编程课上应该教的第一件事(鼓掌)是封装的重要性,以清单常量作为基本示例。
标签: c