C 编程:malloc() 在另一个函数中 [英] C Programming: malloc() inside another function

查看:28
本文介绍了C 编程:malloc() 在另一个函数中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要关于 malloc() 在另一个函数中的帮助.

I need help with malloc() inside another function.

我正在将 指针大小 从我的 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆