【问题标题】:Segmentation fault during resizing two-dimensional dynamically allocated table [duplicate]调整二维动态分配表的大小时出现分段错误[重复]
【发布时间】:2017-04-03 06:57:32
【问题描述】:

我有二维动态分配的表。调整表格大小。

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);
}

输出: 分段错误。

这是调整表格大小的好方法/算法吗?如何省略分段错误错误?

【问题讨论】:

标签: c arrays resize malloc free


【解决方案1】:

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

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
    //...
}

【讨论】:

    猜你喜欢
    • 2017-04-18
    • 1970-01-01
    • 1970-01-01
    • 2021-03-25
    • 2021-08-04
    • 2010-12-27
    • 2011-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多