简体   繁体   English

您不能从 function 内部重新分配 C 中的 memory 块吗?

[英]Can you not realloc a memory block in C from inside of a function?

So, while writeing a program I realised that when using realloc in a function outside of main if the original block of memory was declaired in main it doesnt seem to keep the changes outside of the function.因此,在编写程序时,我意识到当在 main 之外的 function 中使用 realloc 时,如果在 main 中声明了 memory 的原始块,它似乎不会将更改保留在 ZC1C425274E68384F1AB50A 之外。 EG例如

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

Do I need to do something different or should this work fine?我需要做一些不同的事情还是应该可以正常工作? Also this is just example code and is not intended to be runnable此外,这只是示例代码,并非可运行

Extra info I am using MinGW on windows 10额外信息我在 windows 10 上使用 MinGW

You passes to the function the expression &ptr that has the type int ** .您将类型为int **的表达式&ptr传递给 function 。

exampleFunction(&ptr);

But the function parameter has the type int * .但是 function 参数的类型为int *

void exampleFunction(int *ptr)

So the function declaration and its call do not make sense.所以 function 声明及其调用没有意义。

You have to declare and define the function at least like您必须至少像这样声明和定义 function

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

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

}

Though it will be better to use a temporary pointer with the call of realloc because the function can return NULL .尽管在调用realloc时使用临时指针会更好,因为 function 可以返回NULL In this case the original value of *ptr will be lost.在这种情况下, *ptr的原始值将丢失。

So you should declare the function like所以你应该像这样声明 function

//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;

}

You can write like this.你可以这样写。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM