昨天我发布了一个问题:如何在调用的函数内传递指针并为传递的指针分配内存?
从我得到的答案中,我能够理解我犯了什么错误。
现在我面临一个新问题,有人能帮忙吗?
我想动态分配一个二维数组,所以我将一个指向指针的指针从我的
好吧,在从
有人能建议我在这里犯了什么错误吗?
救命啊!
Vikram
来源:
现在我面临一个新问题,有人能帮忙吗?
我想动态分配一个二维数组,所以我将一个指向指针的指针从我的
main()
传递到另一个名为alloc_2D_pixels(...)
的函数中,在那里我使用malloc(...)
和for(...)
循环来为二维数组分配内存。好吧,在从
alloc_2D_pixels(...)
函数返回后,指向指针的指针仍然为空,因此,当我尝试访问或尝试free(...)
指向指针的指针时,程序会挂起。有人能建议我在这里犯了什么错误吗?
救命啊!
Vikram
来源:
main()
{
unsigned char **ptr;
unsigned int rows, cols;
if(alloc_2D_pixels(&ptr, rows, cols)==ERROR) // Satisfies this condition
printf("Memory for the 2D array not allocated"); // NO ERROR is returned
if(ptr == NULL) // ptr is NULL so no memory was allocated
printf("Yes its NULL!");
// Because ptr is NULL, with any of these 3 statements below the program HANGS
ptr[0][0] = 10;
printf("Element: %d",ptr[0][0]);
free_2D_alloc(&ptr);
}
signed char alloc_2D_pixels(unsigned char ***memory, unsigned int rows, unsigned int cols)
{
signed char status = NO_ERROR;
memory = malloc(rows * sizeof(unsigned char** ));
if(memory == NULL)
{
status = ERROR;
printf("ERROR: Memory allocation failed!");
}
else
{
int i;
for(i = 0; i< cols; i++)
{
memory[i] = malloc(cols * sizeof(unsigned char));
if(memory[i]==NULL)
{
status = ERROR;
printf("ERROR: Memory allocation failed!");
}
}
}
// Inserted the statements below for debug purpose only
memory[0][0] = (unsigned char)10; // I'm able to access the array from
printf("\nElement %d",memory[0][0]); // here with no problems
return status;
}
void free_2D_pixels(unsigned char ***ptr, unsigned int rows)
{
int i;
for(i = 0; i < rows; i++)
{
free(ptr[i]);
}
free(ptr);
}