1

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.

1
  • 2
    Correct signature for main is int main(int argc, char *argv[]). The arguments are strings, so need to be converted to int for use in the size calculation. Commented Jul 19, 2022 at 20:42

2 Answers 2

3

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

btw.. the memory allocation could be simplified to int (*arr)[cols] = malloc(sizeof(int[row][cols]));
it is not a 2D array only an array of pointers. It is something completely different
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.