【发布时间】:2016-02-03 13:21:32
【问题描述】:
起初,如果我在函数内释放分配可能听起来很正常,但事实并非如此。当我写这些行时,我找到了一个解决方法,但我想在我的代码中保持一定的同质性,并且更愿意保持它的方式,但你知道工作正常,所以还有其他解决方案或我的解决方法是唯一的选择吗?
主要功能:
void main(void)
{
SHead head; // Custom struct
unsigned char **array = NULL; // pointer to 2D array
allocArray2D(&head, array) // the function signature: (SHead*, unsigned char**)
// here, the array pointer is still NULL (0x0)
//...
return EXIT_SUCCESS;
}
分配函数 malloc 在 21 个 unsigned char* 附近分配了非常少量的内存,并且为每个简单指针分配了 21 个 unsigned char。 在函数内,指针很好,指向正确的地址。
所以我的解决方法是从以下位置修改函数:
void allocArray(SHead* h, unsigned char** arr)
{
int x, y, i;
getsize(head, *x, *y);
arr = (unsigned char**)malloc(sizeof(unsigned char*)*y);
if(arr)
printf(">> Erro allocating memory\n"), return;
for(i =0; i<y; i++)
{
arr[i] = (unsigned char)malloc(sizeof(unsigned char)*x);
}
}
到以下:
unsigned char** allocArray(SHead*)
{
int x, y, i;
unsigned char **arr;
getsize(head, *x, *y);
arr = (unsigned char**)malloc(sizeof(unsigned char*)*y);
if(arr)
printf(">> Erro allocating memory\n"), return;
for(i =0; i<y; i++)
{
arr[i] = (unsigned char)malloc(sizeof(unsigned char)*x);
}
return arr; // returning the address
}
正如我之前所说,我希望在我的代码中保持同质性,并且希望保持与我拥有的其他函数相似的函数签名。我的解决方法工作正常。我想知道这是否是唯一的解决方案,或者我可能遗漏了一些东西。
编辑:在 cmets 之后,我添加了更多代码。
谢谢, 亚历克斯。
【问题讨论】:
-
不应该是
allocArray2D(&head, array);还是错字? -
请出示
allocArray2D函数。 -
提供minimal reproducible example。
*head看起来很不对劲。 -
allocArray2D是什么,它应该做什么?您能尝试创建一个Minimal, Complete, and Verifiable Example 并展示给我们看吗?代码说一千多张图片。 -
又一个添加星星而不是简单地返回结果的示例。通过使用更多的星星,您不会成为更好的 C 程序员。这不是做饭。
标签: c function pointers parameters