在C语言中,你能不能不从函数内部重新分配内存块?

问题描述 投票:0回答:1

所以,在写程序的时候,我意识到,当在main之外的函数中使用realloc时,如果原来的内存块在main中被声明,它似乎不会在函数之外保留变化。

void main()
{

    int *ptr;

    //allocates memory
    ptr = calloc(4, sizeof(int));

    exampleFunction(&ptr);

} //end main


//this function reallocates the memory block of ptr
void exampleFunction(int *ptr)
{

    ptr = realloc(ptr, (sizeof(int) * 10));

} // end exampleFunction

我是否需要做一些不同的事情,或者这样做应该很好? 另外,这只是示例代码,并不打算运行

额外信息我在windows 10上使用MinGW。

c memory mingw
1个回答
2
投票

你将表达式传递给函数 &ptr 属于 int **.

exampleFunction(&ptr);

但函数参数的类型是 int *.

void exampleFunction(int *ptr)

所以函数的声明和调用是没有意义的。

你必须至少像这样声明和定义函数。

//this function reallocates the memory block of ptr
void exampleFunction( int **ptr)
{

    *ptr = realloc( *ptr, (sizeof(int) * 10));

}

虽然使用临时指针与调用的 realloc 因为该函数可以返回 NULL. 在这种情况下,原值为 *ptr 将会丢失。

所以你应该声明这样的函数

//this function reallocates the memory block of ptr
int exampleFunction( int **ptr)
{
    int *tmp = realloc( *ptr, (sizeof(int) * 10));

    int success = tmp != NULL;

    if ( success ) *ptr = tmp;

    return success;

}

0
投票

你可以这样写。

void main()
{

    int *ptr;

    //allocates memory
    ptr = calloc(4, sizeof(int));

   ptr= exampleFunction(ptr);

}

int * exampleFunction(int *ptr)
{
    ptr = realloc(ptr, (sizeof(int) * 10));
  return(ptr);
}
© www.soinside.com 2019 - 2024. All rights reserved.