C 编程:另一个函数中的 malloc() [英] C Programming: malloc() inside another function
问题描述
我需要 malloc()
在另一个函数中方面的帮助.
I need help with malloc()
inside another function.
我将 pointer 和 size 从我的 main()
传递给函数,我想为该指针分配内存从被调用函数内部动态使用 malloc()
,但我看到的是......正在分配的内存是用于在我的被调用函数中声明的指针而不是指针这是在 main()
.
I'm passing a pointer and size to the function from my main()
and I would like to allocate memory for that pointer dynamically using malloc()
from inside that called function, but what I see is that.... the memory, which is getting allocated, is for the pointer declared within my called function and not for the pointer which is inside the main()
.
我应该如何传递一个指向函数的指针并为传递的指针分配内存从被调用函数内部?
How should I pass a pointer to a function and allocate memory for the passed pointer from inside the called function?
我编写了以下代码,得到的输出如下所示.
I have written the following code and I get the output as shown below.
来源:
int main()
{
unsigned char *input_image;
unsigned int bmp_image_size = 262144;
if(alloc_pixels(input_image, bmp_image_size)==NULL)
printf("
Point2: Memory allocated: %d bytes",_msize(input_image));
else
printf("
Point3: 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("
ERROR: Memory allocation did not complete successfully!");
}
printf("
Point1: Memory allocated: %d bytes",_msize(ptr));
return status;
}
程序输出:
Point1: Memory allocated ptr: 262144 bytes
Point2: Memory allocated input_image: 0 bytes
推荐答案
您需要将一个指向指针的指针作为参数传递给您的函数.
You need to pass a pointer to a pointer as the parameter to your function.
int main()
{
unsigned char *input_image;
unsigned int bmp_image_size = 262144;
if(alloc_pixels(&input_image, bmp_image_size) == NO_ERROR)
printf("
Point2: Memory allocated: %d bytes",_msize(input_image));
else
printf("
Point3: 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); /* this line is completely redundant */
printf("
ERROR: Memory allocation did not complete successfully!");
}
printf("
Point1: Memory allocated: %d bytes",_msize(*ptr));
return status;
}
这篇关于C 编程:另一个函数中的 malloc()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!