我需要malloc()inside another function的帮助.

我从main()向函数传递了pointersize,我想从调用的函数内部使用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

推荐答案

需要将指针作为参数传递给函数.

int main()
{
   unsigned char *input_image;
   unsigned int bmp_image_size = 262144;

   if(alloc_pixels(&input_image, bmp_image_size) == NO_ERROR)
     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);      /* this line is completely redundant */
        printf("\nERROR: Memory allocation did not complete successfully!"); 
    } 

    printf("\nPoint1: Memory allocated: %d bytes",_msize(*ptr)); 

    return status; 
} 

C++相关问答推荐

在C中,entry = fgets(entry,sizeof(entry),*pt)是否是错误?

是否可以在C中进行D3 D12申请?

以c格式打印时间戳

如何设置指针指向在函数中初始化的复合文字中的整数?

C中是否有语法可以直接初始化一个常量文本常量数组的 struct 成员?

Win32API Wizzard97 PropSheet_SetWizButton不工作

为什么STM32G474RE上没有启用RCC PLL

如何在不使用其他数组或字符串的情况下交换字符串中的两个单词?

在为hashmap创建加载器时,我的存储桶指向它自己

1处的解析器错误:yacc语法的语法错误

为什么我可以在GCC的标签后声明变量,但不能声明Clang?

致命错误:ASM/rwan ce.h:没有这样的文件或目录.符号链接还不够

S和查尔有什么不同[1]?

在C程序中使用Beaglebone Black UART的问题

具有正确标头的C struct 定义问题

传递给函数的 struct 中的数组

计算时出现奇怪的计算错误;N Select K;在C中

'printf("%s", user_input)' 危险吗?

C Makefile - 如何避免重复提及文件名

cs50拼写器分配中的无限循环