Home > Mobile >  2D Array using Command Line Argument and Dynamic Memory Allocation in C
2D Array using Command Line Argument and Dynamic Memory Allocation in C

Time:07-20

So I wanna create a 2D array where the number of rows and columns are taken by command line argument. Then the array is made using dynamic memory allocation where users give the input.

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

int main(int argc, int *argv[]) {
   int **arr;
   arr = (int **)malloc(*argv[1]*sizeof(int*));
   
   for (int i=0; i<argv[1]; i  )
      arr[i] = (int *)malloc (*argv[2]*sizeof(int));
  
   for (int i=0; i<argv[1]; i  )
      for (int j=0; i<argv[2]; j  )
         scanf("%d", &arr[i][j]);
   
   for (int i=0; i<argv[1]; i  ){
      for (int j=0; i<argv[2]; j  )
         printf("%d ",arr[i][j]);
      printf("\n");}
   
   return 0;
}

However Iam getting segmentation dump every time Iam running this. Can you please explain where Iam doing wrong.

CodePudding user response:

You have an incorrect signature for main. Arguments are provided as an array of pointers to string, so to get the row/col, you need to convert the string to int, for example, using atoi().

You also have an error using i for the second part of the loop when calling scanf.

I've made corrections below and added some minor changes for clarity.

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

int main(int argc, char *argv[]) {
   int **arr;
   if (argc < 3) {
       printf("must supply 2 integer arguments\n");
       return -1;
   }
   
   int rows = atoi(argv[1]);
   int cols = atoi(argv[2]);
   
   printf("rows=%d, cols=%d\n", rows, cols);
   arr = (int **)malloc(rows*sizeof(int*));
   
   for (int i=0; i<rows; i  )
      arr[i] = (int *)malloc (cols*sizeof(int));
  
   for (int i=0; i<rows; i  ) {
      for (int j=0; j<cols; j  ) {
         printf("Value for row %d col %d: ", i 1, j 1);
         scanf("%d", &arr[i][j]);
      }
   }
   
   for (int i=0; i<rows; i  ) {
      for (int j=0; j<cols; j  ) {
         printf("%d ",arr[i][j]);
      }
      printf("\n");
       
   }
   
   return 0;
}

CodePudding user response:

Use array pointers.

int main(int argc, char *argv[]) 
{
   
   int rows = atoi(argv[1]);
   int cols = atoi(argv[2]);

   int (*arr)[cols] = malloc(rows * sizeof(*arr));
   
}
  •  Tags:  
  • c
  • Related