Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // ******************************************
- // * Passing 2D arrays into a function when *
- // * the width is not known at compile time *
- // ******************************************
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- //After input the program calls this function to clear the buffer
- void buff_clr()
- {
- char junk;
- do
- {
- junk=getchar();
- }while(junk!='\n');
- }
- //Just a test function(hence it's name) to test subscripting "by hand"
- void func_test(int *array, int columns, int rows)
- {
- unsigned int i=0,j=0;
- while(1)
- {
- printf("\nInput the coordinates you would like to change:");
- printf("\nRow:");
- scanf("%d",&i);
- buff_clr();
- printf("Column:");
- scanf("%d",&j);
- buff_clr();
- if(i<rows && j<columns)
- {
- break;
- }
- }
- array[i*columns+j]=125;
- }
- int main()
- {
- int n=0,m=0;
- unsigned int i=0,j=0;
- //Prompts for array size values
- printf("Input the matrix size n x m:\n");
- printf("Input No. of columns:");
- scanf("%d",&n);
- buff_clr();
- printf("Input No. of rows:");
- scanf("%d",&m);
- buff_clr();
- //2D array definition
- int array[m][n];
- //seed for rand() function
- //which will give the array random values from 0-10
- srand((unsigned int)time(NULL));
- printf("\n");
- //array initialization
- for(i=0;i<m;i++)
- {
- for(j=0;j<n;j++)
- {
- array[i][j] = rand() % 11;
- }
- }
- //array print
- for(i=0;i<m;i++)
- {
- for(j=0;j<n;j++)
- {
- printf("\t%d",array[i][j]);
- }
- printf("\n");
- }
- //test function call
- func_test(&array[0][0],m,n);
- printf("\n\n");
- //array print
- for(i=0;i<m;i++)
- {
- for(j=0;j<n;j++)
- {
- printf("\t%d",array[i][j]);
- }
- printf("\n");
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment