int row = 5, col =5 ;
arr = (int **) malloc(sizeof(int*) * row);
for (int index=0; index<row; index++)
{
*(arr + index) = (int *) malloc(sizeof(int) * col);
}
我使用这段代码来声明一个双指针数组。如果需要,如何使用 realloc 来增加行和列? 我们不知道将获得多少输入:
void increase(int** arr)
{
*arr = (int *) realloc(*arr, 5 * sizeof (int));
}
我认为它不起作用。我需要重新分配行和列。 我插入了条件:
if(var % 5 == 4)
然后调用函数增加并重新分配,但它似乎不起作用。
最佳答案
使您的代码可重用于 C 中的不同数据类型(int/double)。您需要使用通用数据类型的概念。
要使用通用数据类型,可能需要您实现特定于数据类型的自定义自由函数。对于 int 和 double,您不需要使用自定义特定的免费函数;但如果您是 C 语言新手,免费并不是小事。
要扩展数据结构,您需要定义一个扩展数据结构的函数。检查斯坦福大学的堆栈实现(讲座:[4, 8))https://www.youtube.com/playlist?list=PL9D558D49CA734A02
一个建议。 不要重新转换 malloc() 的输出。不需要! 变化:
arr = (int **) malloc(sizeof(int*) * row);
致:
arr = malloc(sizeof(int*) * row);
关于c - 如何在双指针数组中使用realloc?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41088500/