昨天我发布了一个问题:我应该如何传递指向函数的指针并为被调用函数内部传递的指针分配内存?
从我得到的答案中,我能够理解我在做什么错误.
我现在面临一个新问题,任何人都可以帮忙解决这个问题吗?
我想动态分配一个2D数组,所以我将一个Pointer-to-Pointer从my main()传递给另一个调用的函数alloc_2D_pixels(...),在那里我使用malloc(...)并for(...)循环为2D数组分配内存.
好吧,从alloc_2D_pixels(...)函数返回后,指针指针仍然保持为NULL,所以很自然地,当我尝试访问或尝试free(...)指针到指针时,程序挂起.
谁能告诉我我在这里犯的错误?
救命!!!
维克拉姆
资源:
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 …Run Code Online (Sandbox Code Playgroud)