如何使用的realloc在C中的函数 [英] How to use realloc in a function in C
问题描述
这是什么,我在这里学到大厦:<一href=\"http://stackoverflow.com/questions/13746067/manipulating-dynamic-array-through-functions-in-c\">Manipulating通过功能动态数组用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);
}
调用code,那么看起来像:
Calling code would then look like:
int *data = malloc(4 * sizeof *data);
/* do stuff with data */
increase(&data);
/* more stuff */
free(data);
这篇关于如何使用的realloc在C中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!