[英]Can you not realloc a memory block in C from inside of a function?
因此,在编写程序时,我意识到当在 main 之外的 function 中使用 realloc 时,如果在 main 中声明了 memory 的原始块,它似乎不会将更改保留在 ZC1C425274E68384F1AB50A 之外。 例如
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
您将类型为int **
的表达式&ptr
传递给 function 。
exampleFunction(&ptr);
但是 function 参数的类型为int *
。
void exampleFunction(int *ptr)
所以 function 声明及其调用没有意义。
您必须至少像这样声明和定义 function
//this function reallocates the memory block of ptr
void exampleFunction( int **ptr)
{
*ptr = realloc( *ptr, (sizeof(int) * 10));
}
尽管在调用realloc
时使用临时指针会更好,因为 function 可以返回NULL
。 在这种情况下, *ptr
的原始值将丢失。
所以你应该像这样声明 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;
}
你可以这样写。
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.