例如,我有以下接口...
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)数组 (Vertex out[])
它最初是根据多边形中顶点的数量建立的。例如:
out = (Vertex *)malloc(vertexInPolygon * sizeof(Vertex))
其中vertexInPolygon是多边形中顶点的数量整数。
length是一个应该被称为size的打字错误。
Size是一个整数指针。
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
分别是什么意思? - evgenyrealloc
抱怨它没有动态分配。那么... 它是否被动态分配了?你必须先使用malloc
才能后续使用realloc
。 - Daniel BrockmaninsertVertex()
之前,您能否展示一下length
或size
的定义? - Timothy Jonesint *size = 0
会将size
初始化为 NULL,并且不会给你一个指向值为 0 的int
指针。除非你之后将其指向一个实际的int
,否则这可能是你的问题所在。 - Dmitri