如何在C中的函数中使用realloc [英] How to use realloc in a function in C
问题描述
以我在这里学到的知识为基础:通过 C 中的函数操作动态数组.
Building on what I learned here: Manipulating dynamic array through functions in C.
void test(int data[])
{
data[0] = 1;
}
int main(void)
{
int *data = malloc(4 * sizeof *data);
test(data);
return 0;
}
这很好用.但是,我也尝试在函数中使用 realloc
.
This works fine. However, I am also trying to using realloc
in a function.
void increase(int data[])
{
data = realloc(data, 5 * sizeof *data);
}
这符合但程序在运行时崩溃.
This complies but the program crashes when run.
问题
我应该如何在函数中使用 realloc?
How should I be using realloc in a function?
我知道我应该将 realloc
的结果分配给一个变量并首先检查它是否为 NULL
.这只是一个简化的例子.
I understand that I should assign the result of realloc
to a variable and check if it is NULL
first. This is just a simplified example.
推荐答案
您想修改 int*
(您的数组)的值,因此需要将指向它的指针传递到您的 增加
功能:
You want to modify the value of an int*
(your array) so need to pass a pointer to it into your increase
function:
void increase(int** data)
{
*data = realloc(*data, 5 * sizeof int);
}
调用代码看起来像:
int *data = malloc(4 * sizeof *data);
/* do stuff with data */
increase(&data);
/* more stuff */
free(data);
这篇关于如何在C中的函数中使用realloc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!