c - 如何在双指针数组中使用realloc?

标签 c algorithm

 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)

然后调用函数增加并重新分配,但它似乎不起作用。

最佳答案

  1. 使您的代码可重用于 C 中的不同数据类型(int/double)。您需要使用通用数据类型的概念。

  2. 要使用通用数据类型,可能需要您实现特定于数据类型的自定义自由函数。对于 int 和 double,您不需要使用自定义特定的免费函数;但如果您是 C 语言新手,免费并不是小事。

  3. 要扩展数据结构,您需要定义一个扩展数据结构的函数。检查斯坦福大学的堆栈实现(讲座:[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/

相关文章:

c - 共享库 : break the ABI compatibility without breaking API compatibility

c - 如何惯用地使用 C 指针包装函数?

c - 为什么我在这里 fork 超过 5 次?

algorithm - 如何表示隐含关系?

javascript - 对于正则表达式模式,如何确定与该模式匹配的最长字符串的长度?

c - 用C写shell,如何区分交互模式和批处理模式

c - 如何在C程序中显示当前时间,在CodeVisionAVR中编译

algorithm - 如何在不同目录的多个图像中读取和运行算法?

algorithm - 在递归/缩进树数据结构之间转换

python - 创建表示 3 位二进制字符串的所有组合的最小图形