i was trying to pass a 2D array to a function using commandline parameters. first i have to escape the prototype error so used "int arr[][3]" but could not get through the argv error which is mentioned in the screenshot here. is it possible to pass a 2D array the way i am trying or am i just banging my head onto the wall enter image description here
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
void twoD_array(int arr[][3]);
int main(int argc,char * argv[])
{
if(argc == 1)
{
printf("command line argument fails\n");
return 0;
}
int i,j;
int arr[atoi(argv[1])][atoi(argv[2])];
twoD_array(arr);
printf("Your 2D array is\n");
for(i = 0; i < atoi(argv[1]); i )
{
for(j = 0;j < atoi(argv[2]); j )
{
printf("%d ",arr[i][j]);
}
printf("\n");
}
}
void twoD_array(int arr[atoi(argv[1])][atoi(argv[2])])
{
int i,j;
printf("enter elements of 2D array\n");
for(i = 0; i < atoi(argv[1]); i )
{
for(j = 0;j < atoi(argv[2]); j )
{
scanf("%d",&arr[i][j]);
}
}
}
CodePudding user response:
You cannot define a function like this:
void twoD_array(int arr[atoi(argv[1])][atoi(argv[2])])
{
…
}
The variable argv
is not in scope (undefined), and you can't use function calls like that in the function parameter list.
You could use VLA (variable-length array) notation, though:
void twoD_array(int rows, int cols, int arr[rows][cols])
{
…
}
Support for this was non-existent in C90, is mandatory in C99, and is optional in C11 and C18. C23 will make VLA support in parameter lists mandatory once more, but support for local (automatic) allocation of stack VLA variables will be optional (but they can always be allocated dynamically via malloc()
et al).
See C11 §6.7.6.2 Array declarators and §6.7.6.3 Function declarators (including prototypes). They are not the most easily read sections of the standard, though.
CodePudding user response:
final answer:
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
void twoD_array(int arr[][3]);
int ROW,COL;
int main(int argc,char * argv[])
{
if(argc == 1)
{
printf("command line argument fails\n");
return 0;
}
int i,j;
int arr[atoi(argv[1])][atoi(argv[2])];
ROW = atoi(argv[1]);
COL = atoi(argv[2]);
twoD_array(arr);
printf("Your 2D array is\n");
for(i = 0; i < atoi(argv[1]); i )
{
for(j = 0;j < atoi(argv[2]); j )
{
printf("%d ",arr[i][j]);
}
printf("\n");
}
}
void twoD_array(int arr[ROW][COL])
{
int i,j;
printf("enter elements of 2D array\n");
for(i = 0; i < ROW; i )
{
for(j = 0;j < COL; j )
{
scanf("%d",&arr[i][j]);
}
}
}