【发布时间】:2018-11-30 18:23:12
【问题描述】:
我已经为 malloc 和 realloc 背后的想法苦苦挣扎了很长一段时间,目前我在动态创建结构数组时遇到了问题。我有一个struct triangle,它本身由struct coordinates 的数组组成。我希望能够拥有一个足够大的triangles 数组,但是每次我尝试增加数组的长度时,似乎什么都没有发生。 Realloc 不会失败,malloc 也不会。但是新的三角形没有插入我的数组中。这是我的代码供参考。
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>
struct coordinate {
int x;
int y;
};
struct triangle {
struct coordinate point[3];
};
static size_t size = 0;
static void addTriangle(struct triangle **triangles, struct triangle *t) {
struct triangle *ts = (struct triangle*) realloc(*triangles, (size+1) * sizeof(struct triangle));
if(ts == NULL) {
free(ts);
exit(EXIT_FAILURE);
}
*triangles = ts;
triangles[size] = t;
size++;
}
int main() {
struct triangle* triangles = (struct triangle *) malloc(sizeof(struct triangle));
if(triangles == NULL) {
free(triangles);
exit(EXIT_FAILURE);
}
for(int i = 0; i < 2; i++) {
struct coordinate *a = malloc(sizeof(struct coordinate));
a->x = 1 * i;
a->y = 2 * i;
struct coordinate *b = malloc(sizeof(struct coordinate));
b->x = 3 * i;
b->y = 4 * i;
struct coordinate *c = malloc(sizeof(struct coordinate));
c->x = 5 * i;
c->y = 6 * i;
struct triangle *t = malloc(sizeof(struct triangle));
t->point[0] = *a;
t->point[1] = *b;
t->point[2] = *c;
addTriangle(triangles, t);
}
}
我已经尝试了我发现的所有变体,但我宁愿不要盲目地输入 & 和 * 直到发生某些事情。
【问题讨论】:
-
你能给出结构坐标和结构三角形的定义吗?
-
当然,我将它们添加到我的代码示例中。对此感到抱歉
-
尝试将 tangles 的地址发送到 add_traingles 函数。即addTrangles(&tangles, t);
-
addTriangle(triangles, t);您的编译器应该抱怨第一个参数的间接级别不同。你期待一个struct triangle **,但你传递了一个struct triangle *。您应该始终在编译器中启用警告。使用 -Wall -Wextra -
与您的问题无关,但在为坐标分配内存时会造成内存泄漏。你可以简单地使用一个变量。不需要指针。
标签: c arrays struct malloc realloc