调整二维动态分配大小时出现分段错误 table

Segmentation fault during resizing two-dimensional dynamically allocated table

我有二维动态分配 table。调整 table.

的大小

1) 创建一个新的。

2) 删除之前的指针,分配内存。

3) 分配新指针。

代码:

#include <stdio.h>
#include <stdlib.h>

int** create(int rows, int columns)
{
    int **tab = (int**)malloc(rows * sizeof(int*));
    int i=0;
    for(;i<rows; ++i)
    {
        tab[i] = (int*)malloc(columns * sizeof(int));   /* tab[i] = (int*)calloc(columns , sizeof(int)); */
    }

    return tab;
}
void deleteTab(int **tab, int rows)
{
    int i=0;
    for(;i<rows;++i)
    {
        free(tab[i]);
    }
    free(tab);
}
void resize(int **tab, int oldRows, int newRows, int newColumns)
{
    int **newTab=create(newRows, newColumns);
    deleteTab(tab, oldRows);
    tab=newTab;
}
void printTab(int **tab, int rows, int columns)
{
    int i=0, j=0;
    for(i=0;i<rows;++i, printf("\n"))
    {
        for(j=0;j<columns;++j)
        {
            printf("%i ", tab[i][j]);
        }
    }
}
int main()
{
    int **tab=create(4,7);
    resize(tab,4,8,9);
    int i=0, j=0;
    for(i=0;i<8;++i)
    {
        for(j=0;j<9;++j)
        {
            tab[i][j]=3;
        }
    }
    printTab(tab,8,9);
}

输出: 分段错误。

调整 table 的大小是否合适 way/algorithm?如何省略分段错误?

resize 必须 return newtab。参数按值传递。或者您可以将 tab 作为 table 的指针并像这样更改您的代码

void resize(int ***tab, int oldRows, int newRows, int newColumns)
{
    int **newTab=create(newRows, newColumns);
    deleteTab(*tab, oldRows);
    *tab=newTab;
}

并这样称呼它:

int main()
{
    int **tab=create(4,7);
    resize(&tab,4,8,9); //note 'tab' now pass-by-pointer
    //...
}