这个问题在这里已有答案:
我已经定义了struct Node和createNode函数。
typedef struct {
int r, c;
int val;
struct Node* down, *right;
} Node;
typedef Node* NodePointer;
NodePointer createNode(int r,int c,int val) {
NodePointer p = (NodePointer)malloc(sizeof(NodePointer));
if (p != NULL) {
p->r = r;
p->c = c;
p->val = val;
p->down = p->right = NULL;
}
return p;
}
然后当我尝试在main函数中使用它时
int i = 0;
NodePointer* rows = (NodePointer*)malloc(50*sizeof(NodePointer));
for (i = 0; i < 20; i++) {
rows[i] = createNode(i,i+10,i*i);
}
它引发了运行时错误,但是当我像这样改变循环时(更改是for for循环 - 只执行一次):
for (i = 0; i < 1; i++) {
rows[i] = createNode(i,i+10,i*i);
}
它没有抛出错误。所以我问我做错了什么;错误:
Zad1: malloc.c:2374: sysmalloc: Assertion `(old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 *(sizeof(size_t))) - 1)) & ~((2 *(sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long) old_end & pagemask) == 0)' failed.
改变这个:
NodePointer p = (NodePointer)malloc(sizeof(NodePointer));
对此:
Node p = malloc(sizeof(Node));
因为你想要分配Node
类型的元素,而不是NodePointer
。
提示:转换malloc()
的返回不会导致错误,但你不应该这样做,如Do I cast the result of malloc?中所讨论的
PS:当你为p
和rows
分配相同的类型时,是不是觉得很奇怪? ;)