0

Can't increase rows in 2d array, but columns is ok.

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

it is working:

void increasecolumn(int ** mas, int* n, int m){
    for (int i = 0; i < m; i++){
        int* tmp = realloc(mas[i], sizeof (*mas[i]) * ((*n) + 1));
         if (tmp){
            mas[i] = tmp;
         }
     }
     (*n) = (*n) + 1;
 }

but increasing rows failed

 void increaserow(int ** mas, int n, int* m){
    int ** tmp = realloc(mas, sizeof(*mas) * ((*m) + 1));
     if (tmp){
        mas = tmp;
         for (int i = 0; i < 1; i++){
             mas[(*m) + i] = malloc(sizeof(*mas[(*m) + i]) * n);
         }
     }
     (*m) = (*m) + 1;
 }
 int main(int argc, char * argv[]) {
     int n = 3; // columns
     int m = 2; // rows
     int** mas = malloc(m*sizeof(*mas));
     for(int i = 0; i < m; i++){
         mas[i] = malloc(n*sizeof(*(mas[i])));
     }
     for(int i = 0; i < m; i++){
         for(int j = 0; j < n; j++){
             mas[i][j] = 0;
             printf("%d ", mas[i][j]);
    }
    printf("\n");
}
printf("\n");

increasecolumn(mas, &n, m);
for (int i = 0; i < m; i++){
    mas[i][n-1] = 1;
}

increaserow(mas, n, &m); // problem is here
for (int j = 0; j < n; j++){
    mas[m-1][j] = 0;
}

for(int i = 0; i < m; i++){
    for(int j = 0; j < n; j++){
        printf("%d ", mas[i][j]);
    }
    printf("\n");
}
   system("pause");
   return 0;
}

I use this answer Resizing 2D Arrays in C like an example, something wrong.


The GNU Project Debugger on Windows:

warning: FTH: (9152): * Fault tolerant heap shim applied to current process. This is usually due to previous crashes. *

0 0 0
0 0 0

Program received signal SIGSEGV, Segmentation fault.
0x0000000000401821 in main (argc=1, argv=0x7f1990) at D:\III Курс! II СЕМЕСТР\МатМодДослОп\stud\Untitled2.c:47
47: mas[m-1][j] = 0;


Community
  • 1
  • 1
  • as usually, the answer is `valgrind` – Dariusz May 12 '17 at 08:28
  • "Something wrong" is a little bit unspecific. Compiler errors? Runtime errors (e.g. a crash)? Wrong behavior? Please, describe your problem in more detail. I assume you already tried to identify the problem on your side using a debugger of your choice. So, what have you found out and what's missing/unclear? – Scheff's Cat May 12 '17 at 08:40
  • it've helped me, but I dont understand why it earned **void** for columns? – Artur Yuzkiv May 12 '17 at 09:04

0 Answers0