Question
Passing, filling and printing 2D arrays of varaible size with functions in C language. In my first example below I declare an array[3][3] and send
Passing, filling and printing 2D arrays of varaible size with functions in C language.
In my first example below I declare an array[3][3] and send to fillArray() and printArray() and it works fine. In the second example I ask the user to give an integer wich becomes "size" and use declare array[size][size] and send it to functions but I get error (use of undeclared indetifier "size"). Can some one show me how passing 2D array with a variable size?
First example works:
#include
/* Fills array */ void fillArray(int a[][3]) { printf("Enter 9 integers "); int i, j; for (i=0; i<3; i++) { for (int j=0; j<3; j++) { scanf("%i",&a[i][j]); } } }
/* prints array */ void printArray(int a[][3]) { printf("You array is "); int i, j; for (i=0; i<3; i++) { for (int j=0; j<3; j++) { printf("%i ",a[i][j]); } printf(" "); } }
int main(int argc, char **argv) { int myArray[3][3]; fillArray(myArray); printArray(myArray); return 0; }
Second example doesn't work
#include
/* get size input */ int getSize() { int input; printf("Enter integer N for your N X N array: "); scanf("%i",&input); printf("Size = %i ", input); return input; } /* Fills array */ void fillArray(int a[][size], int size) { printf("Enter your array data as integers "); int i, j; for (i=0; i { for (int j=0; j { scanf("%i",&a[i][j]); } } }
/* prints array */ void printArray(int a[][size], int size) { printf("You array is "); int i, j; for (i=0; i { for (int j=0; j { printf("%i ",a[i][j]); } printf(" "); } }
int main(int argc, char **argv) { /* get size */ int size; size = getSize(); int myArray[size][size]; fillArray(myArray, size); printArray(myArray, size); return 0; }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started