【问题标题】:Can you not realloc a memory block in C from inside of a function?您不能从函数内部重新分配 C 中的内存块吗?
【发布时间】:2020-08-16 04:23:58
【问题描述】:

所以,在编写程序时,我意识到当在 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 Programming: malloc() inside another function
  • 尽量让您的程序保持 0(零)警告。现在你收到了警告,不想阅读它们,而是更愿意寻求帮助。
  • 所以,正如我在原始帖子中所说的那样,这是示例代码,而不是我的实际代码,我想确保这是我可以做的可行的事情

标签: c pass-by-reference dynamic-memory-allocation realloc


【解决方案1】:

你可以这样写。

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);
}

【讨论】:

  • 你是对的:这是一个可行的替代解决方案......但它错过了 OP 尝试通过&ptr(OK)......但随后未能 a)声明参数为int **ptr 和b)分配给*ptr = realloc(...)(因此出现错误)。
  • 是的,先生,我知道这一点。我只是想提供一个更简单的解决方案,感谢您的纠正。 @FoggyDay
  • 老实说,我更喜欢这个 dolution,它更简单,尽管来自另一个的错误检查很高兴我已经知道如何做到这一点,但这并不是我真正想要的。
【解决方案2】:

您将具有int ** 类型的表达式&ptr 传递给函数。

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;

}

【讨论】:

  • 好的,所以您需要 dto 取消引用,然后传回新地址?我曾向某人建议过,但他们说我不能这样做。
  • @PaulGeoghegan 如果要更改函数中的对象,则需要通过引用传递它,在 C 中意味着传递指向该对象的指针。如果要更改函数中的指针 ptr,则必须将指针传递给该指针 ptr,例如 exampleFunction( &ptr );
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-29
  • 2013-10-20
  • 1970-01-01
  • 1970-01-01
  • 2016-07-29
  • 2021-04-08
  • 2019-05-02
相关资源
最近更新 更多