Guest User

Untitled

a guest
Oct 16th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. // ******************************************
  2. // * Passing 2D arrays into a function when *
  3. // * the width is not known at compile time *
  4. // ******************************************
  5.  
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <time.h>
  9.  
  10. //After input the program calls this function to clear the buffer
  11. void buff_clr()
  12. {
  13. char junk;
  14. do
  15. {
  16. junk=getchar();
  17. }while(junk!='\n');
  18.  
  19. }
  20.  
  21. //Just a test function(hence it's name) to test subscripting "by hand"
  22. void func_test(int *array, int columns, int rows)
  23. {
  24. unsigned int i=0,j=0;
  25. while(1)
  26. {
  27. printf("\nInput the coordinates you would like to change:");
  28. printf("\nRow:");
  29. scanf("%d",&i);
  30. buff_clr();
  31. printf("Column:");
  32. scanf("%d",&j);
  33. buff_clr();
  34. if(i<rows && j<columns)
  35. {
  36. break;
  37. }
  38. }
  39. array[i*columns+j]=125;
  40. }
  41.  
  42. int main()
  43. {
  44. int n=0,m=0;
  45. unsigned int i=0,j=0;
  46.  
  47. //Prompts for array size values
  48. printf("Input the matrix size n x m:\n");
  49. printf("Input No. of columns:");
  50. scanf("%d",&n);
  51. buff_clr();
  52. printf("Input No. of rows:");
  53. scanf("%d",&m);
  54. buff_clr();
  55.  
  56. //2D array definition
  57. int array[m][n];
  58.  
  59. //seed for rand() function
  60. //which will give the array random values from 0-10
  61. srand((unsigned int)time(NULL));
  62.  
  63. printf("\n");
  64.  
  65. //array initialization
  66. for(i=0;i<m;i++)
  67. {
  68. for(j=0;j<n;j++)
  69. {
  70. array[i][j] = rand() % 11;
  71. }
  72. }
  73.  
  74. //array print
  75. for(i=0;i<m;i++)
  76. {
  77. for(j=0;j<n;j++)
  78. {
  79. printf("\t%d",array[i][j]);
  80. }
  81. printf("\n");
  82. }
  83.  
  84. //test function call
  85. func_test(&array[0][0],m,n);
  86.  
  87. printf("\n\n");
  88.  
  89. //array print
  90. for(i=0;i<m;i++)
  91. {
  92. for(j=0;j<n;j++)
  93. {
  94. printf("\t%d",array[i][j]);
  95. }
  96. printf("\n");
  97. }
  98.  
  99. return 0;
  100. }
Add Comment
Please, Sign In to add comment