我需要有关 malloc()
在另一个函数中 的帮助。
我将一个指针和大小从我的main()
传递给函数,我想为那个指针分配内存从被调用函数内部动态使用 malloc()
,但我看到的是......正在分配的内存用于在我的被调用函数中声明的指针,而不是指针在 main()
中。
我应该如何将指针传递给函数并为传递的指针分配内存从被调用函数内部?
我编写了以下代码并得到了如下所示的输出。
来源:
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
最佳答案
How should I pass a pointer to a function and allocate memory for the passed pointer from inside the called function?
问问自己:如果您必须编写一个必须返回 int
的函数,您会怎么做?
你要么直接返回:
int foo(void)
{
return 42;
}
或者通过添加级别indirection 通过输出参数返回它(即,使用 int*
而不是 int
):
void foo(int* out)
{
assert(out != NULL);
*out = 42;
}
所以当你返回一个指针类型(T*
)时,它是一样的:你要么直接返回指针类型:
T* foo(void)
{
T* p = malloc(...);
return p;
}
或者您添加一个间接级别:
void foo(T** out)
{
assert(out != NULL);
*out = malloc(...);
}
关于C 编程 : malloc() inside another function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2838038/