【发布时间】:2011-09-27 01:38:39
【问题描述】:
我知道如何构建动态分配的数组,但不知道如何扩展它们。
例如我有如下界面..
void insertVertex( vertex p1, vertex out[], int *size);
此方法获取一个顶点并将其存储到 out 数组中。存储顶点后,我会增加未来调用的长度计数。
p1 - 是我要添加的顶点。
out[] - 是我需要存储的数组(总是满的)
length - 当前长度
顶点定义为..
typedef struct Vertex{
int x;
int y;
} Vertex;
这是我在 Java 中使用的..
Vertex tempOut = new Vertex[size +1];
//Code to deep copy each object over
tempOut[size] = p1;
out = tempOut;
这是我相信我可以在 c.. 中使用的东西。
out = realloc(out, (*size + 1) * sizeof(Vertex));
out[(*size)] = p1;
但是,我不断收到一条错误消息,指出对象不是动态分配的。
我找到了一个可以解决这个问题的解决方案。我没有使用 Vertex*,而是切换到 Vertex** 并存储指针与顶点。但是,在切换所有内容之后,我发现我忽略了这样一个事实,即单元测试将为我提供一个必须存储所有内容的 Vertex out[]。
我也尝试了以下方法,但没有成功。
Vertex* temp = (Vertex *)malloc((*size + 1) * sizeof(Vertex));
for(int i = 0; i < (*size); i++)
{
temp[i] = out[i];
}
out = temp;
但是,无论我在这两个之后测试时做什么,返回的数组都没有改变。
更新 - 要求的信息
out - 定义为一个顶点数组(Vertex out[])
它最初是用我的多边形中的顶点数构建的。例如。
out = (Vertex *)malloc(vertexInPolygon * sizeof(Vertex))
其中 vertexInPolygon 是多边形中顶点数的整数。
长度是一个错字,应该是大小。
大小是一个整数指针
int *size = 0;
每当一个顶点在裁剪平面中时,我们将它添加到顶点数组中,并将大小增加一。
更新
为了更好地解释我自己,我想出了一个简短的程序来展示我正在尝试做的事情。
#include <stdio.h>
#include <stdlib.h>
typedef struct Vertex {
int x, y;
} Vertex;
void addPointerToArray(Vertex v1, Vertex out[], int *size);
void addPointerToArray(Vertex v1, Vertex out[], int *size)
{
int newSize = *size;
newSize++;
out = realloc(out, newSize * sizeof(Vertex));
out[(*size)] = v1;
// Update Size
*size = newSize;
}
int main (int argc, const char * argv[])
{
// This would normally be provided by the polygon
int *size = malloc(sizeof(int)); *size = 3;
// Build and add initial vertex
Vertex *out = (Vertex *)malloc((*size) * sizeof(Vertex));
Vertex v1; v1.x = 1; v1.y =1;
Vertex v2; v2.x = 2; v2.y =2;
Vertex v3; v3.x = 3; v3.y =3;
out[0] = v1;
out[1] = v2;
out[2] = v3;
// Add vertex
// This should add the vertex to the last position of out
// Should also increase the size by 1;
Vertex vertexToAdd; vertexToAdd.x = 9; vertexToAdd.y = 9;
addPointerToArray(vertexToAdd, out, size);
for(int i =0; i < (*size); i++)
{
printf("Vertx: (%i, %i) Location: %i\n", out[i].x, out[i].y, i);
}
}
【问题讨论】:
-
out定义为什么?length和size是什么? -
你说
realloc抱怨它不是动态分配的。所以……是吗?您必须先使用malloc,才能稍后使用realloc。 -
你能否在
length或size传递给insertVertex()之前显示它的定义 -
evgeny out 定义为... Vertex *out = (Vertex *)malloc(sizeof(Vertex) * numOfVerInPolygon) 其中 numOfVerInPolygon 是多边形中的顶点数。 Daniel Brockman 是的,它是用 malloc 定义的。在通过之前,它被定义如下。 Vertex *out = (Vertex *)malloc(sizeof(Vertex) * numOfVerInPolygon) TimothyJones 抱歉,长度和大小是一回事。我更新了帖子,以便所有内容都使用大小。 size 从零开始: int *size = 0;当我们遍历每个顶点时,如果它在剪切平面中,则在添加到 out[](Vertex) 后大小会增加一
-
int *size = 0将使用 NULL 初始化大小,并将其指向任何内容 - 不会给您指向设置为 0 的int的指针。除非您将其指向实际的int稍后,这可能是您的问题。
标签: c