我需要malloc()
inside another function的帮助.
我从main()
向函数传递了pointer和size,我想从调用的函数内部使用malloc()
为该指针动态分配内存,但我看到的是.正在分配的内存是为我调用的函数中声明的指针分配的,而不是为main()
内的指针分配的.
我应该如何将指针传递给函数并为传递的指针from inside the called function分配内存?
我已经编写了以下代码,并得到如下所示的输出.
SOURCE:
int main()
{
unsigned char *input_image;
unsigned int bmp_image_size = 262144;
if(alloc_pixels(input_image, bmp_image_size)==NULL)
printf("\nPoint2: Memory allocated: %d bytes",_msize(input_image));
else
printf("\nPoint3: Memory not allocated");
return 0;
}
signed char alloc_pixels(unsigned char *ptr, unsigned int size)
{
signed char status = NO_ERROR;
ptr = NULL;
ptr = (unsigned char*)malloc(size);
if(ptr== NULL)
{
status = ERROR;
free(ptr);
printf("\nERROR: Memory allocation did not complete successfully!");
}
printf("\nPoint1: Memory allocated: %d bytes",_msize(ptr));
return status;
}
程序输出:
Point1: Memory allocated ptr: 262144 bytes
Point2: Memory allocated input_image: 0 bytes