Command Line Arguments string to integer Two values will be passed to the main f
ID: 3811468 • Letter: C
Question
Command Line Arguments string to integer Two values will be passed to the main function from the command line. These values will be the number of rows and columns needed to create a 2 dimensional array. Assume that argv[1] contains the value for rows and that argv[2] contains the value for columns. Write a C program that reads the command line arguments, converts the character strings to integers, and displays the integer values for rows and columns. This program should only have a single function named main. You will need to use the atoi function to convert strings to integers. Run the included example atoi01.c to understand what this function returns for various input strings. For more information: http://www.cplusplus.com/reference/cstdlib/atoi/?kw=atoiExplanation / Answer
#include <stdio.h>
#include <stdlib.h>
//Main function using command line argument
int main(int argc , char *argv[])
{
//Converts command line argument to integer
int row = atoi(argv[1]);
int col = atoi(argv[2]);
int r, c;
//Allocate memory for rows
int **array = (int **)malloc(sizeof(int *) * row);
//Allocate memory for columns
for(r = 0; r < row; r++)
{
array[r] = (int *)malloc(sizeof(int) * col);
}//End of for loop
//Accept data
printf(" Enter %d data ", (row * col));
for(r = 0; r < row; r++)
{
for(c = 0; c < col; c++)
scanf("%d", &array[r][c]);
}//End of for loop
//Display data
printf(" Matrix contains: ");
for(r = 0; r < row; r++)
{
for(c = 0; c < col; c++)
printf("%4d", array[r][c]);
printf(" ");
}//End of for loop
return 0;
}//End of main
If in command line user enters 2 for row as first argument and 3 for column as second argument
Output:
Enter 6 data
10
20
30
2
3
4
Matrix contains:
10 20 30
2 3 4