1

I`ve got two-dimensional, dynamically allocated table. Resize the table.

1) Create new one.

2) Delete previous pointer, allocated memory.

3) Assign new pointer.

Code:

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

Output: Segmentation fault.

Is it a good way/algorithm to resize the table? How to omit segmentation fault error?

user2856064
  • 541
  • 1
  • 8
  • 25
  • 3
    `resize` should return `newTab` instead of assigning to the **local** `tab`. – StoryTeller - Unslander Monica Apr 03 '17 at 06:59
  • Also there is no apparent reason why you should use pointer-to-pointer here in the first place. Please see [Correctly allocating multi-dimensional arrays](http://stackoverflow.com/questions/42094465/correctly-allocating-multi-dimensional-arrays). – Lundin Apr 03 '17 at 07:57

1 Answers1

0

resize must return newtab. the parameter is passed by value. or you can make tab as a pointer of your table and change your code like this

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

and call it like this:

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