【发布时间】:2019-05-23 01:44:29
【问题描述】:
我正在尝试使用 realloc 创建结构的动态数组(在本例中为图片)。我想在函数中做,但有一个问题: main 中的变量不会被这个函数改变。指针一定有问题,但我找不到。 PS:函数 UploadFile 工作正常。 有一个功能:
int AddPicture(struct Picture ***tab, int *PicCounter)
{
struct Picture *temp;
struct Picture pic;
(*PicCounter)++;
temp = realloc(*tab, (*PicCounter) *sizeof(*temp));
if (temp != NULL)
{
UploadFile(&pic);
**tab = temp;
(*tab)[*PicCounter-1]->name = pic.name;
(*tab)[*PicCounter-1]->type[0] = pic.type[0];
(*tab)[*PicCounter-1]->type[1] = pic.type[1];
(*tab)[*PicCounter-1]->width = pic.width;
(*tab)[*PicCounter-1]->height = pic.height;
(*tab)[*PicCounter-1]->scale = pic.scale;
(*tab)[*PicCounter-1]->table = pic.table;
}
else {
printf("Memory reallocation error");
free(temp);
return 1;
}
return 0;
}
我在 main 中是这样称呼它的:
struct Picture *tabofpics;
int piccounter = 0;
tabofpics = malloc(1 * sizeof(*tabofpics));
AddPicture(&tabofpics,&piccounter);
感谢您的帮助。
编辑: 我试过 **tab 而不是 ***tab 并且 main 中的值是正确的,但它的行为就像内存没有正确重新分配,即使 realloc 不返回 NULL。
int AddPicture(struct Picture **tab, int *PicCounter)
{
struct Picture *temp;
struct Picture pic;
(*PicCounter)++;
temp = realloc(*tab, (*PicCounter) * sizeof(*temp));
if (temp != NULL)
{
UploadFile(&pic);
*tab = temp;
tab[*PicCounter - 1]->name = pic.name;
tab[*PicCounter - 1]->type[0] = pic.type[0];
tab[*PicCounter - 1]->type[1] = pic.type[1];
tab[*PicCounter - 1]->width = pic.width;
tab[*PicCounter - 1]->height = pic.height;
tab[*PicCounter - 1]->scale = pic.scale;
tab[*PicCounter - 1]->table = pic.table;
}
else {
printf("Memory reallocation error");
free(*tab);
return 1;
}
return 0;
}
我们的想法是在程序中放入任意数量的图片,对其进行一些操作然后离开。必须有功能可以在用户需要时添加和删除图片,但是当我第二次在参数中使用 **tab 调用函数时,我会得到访问冲突位置,所以正如我之前提到的,realloc 不能正常工作。
【问题讨论】:
-
为什么
tab是三重指针?似乎双指针就足够了。特别是因为您根据Picture的大小分配内存,而不是Picture *。 -
我认为编译器警告应该给出答案。而且似乎不知道要添加多少张图片,在这种情况下,也许链表会更好?每个节点都是关于你的图片的信息
-
struct Picture ***tab-->struct Picture **tab -
@IgorZ 不要只是尝试解决问题。想一想,先试着理解底层的概念。检查我的答案。
-
@IharobAlAsimi,在分析时值得考虑考虑,但实际上它不是指数的,它是您使用的最大两倍...所以如果您正在处理 1gb 数据集您可能有一个 1gb 的缓冲区未使用,但在现代 VM 环境中这通常是可以的,比复制 .9gb 缓冲区 10 次要好得多