Advertisement
ben1939

תרגיל 6 סעיף ב שדרוג

Dec 31st, 2013
440
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3.  
  4. /*
  5.  
  6. *Name: Tomer Kopf Adar
  7.  
  8. *ID: 304821952
  9.  
  10. */
  11.  
  12. // allocates a dynamic 2d array (array of arrays)
  13. int** init_2darray(int numOfRow, int numOfCol) {
  14.  
  15.     int i, j;
  16.     int** array = (int**) malloc (sizeof(int*)*numOfRow);
  17.     if (array==NULL)
  18.         return NULL;
  19.     for (i=0;i<numOfRow;i++) {
  20.         array[i] = (int*) calloc (numOfCol,sizeof(int));
  21.         if (array[i]==NULL) {
  22.             for (j=0;j<i;j++)
  23.                 free(array[j]);
  24.             free(array);
  25.             return NULL;       
  26.         }
  27.     }
  28.     return array;
  29.  
  30. }
  31.  
  32. // frees a dynamic 2d array
  33. void free_2darray(int** array, int numOfRow) {
  34.  
  35.     int i;
  36.     for (i=0;i<numOfRow;i++)
  37.         free(array[i]);
  38.     free(array);
  39.  
  40. }
  41.  
  42. // prints a 2d array
  43. void print_2darray(int** array, int numOfRow, int numOfCol) {
  44.  
  45.     int i, j;
  46.     for (i=0;i<numOfRow;i++) {
  47.         for (j=0;j<numOfCol;j++)
  48.             printf("%10d",array[i][j]);
  49.         printf("\n");
  50.     }
  51.  
  52. }
  53.  
  54. // modifies a value of a 2d array
  55. // if index is out of current bounds, extends the array to the minimum required size
  56. int** add_to_2darray(int** array, int* numOfRow, int* numOfCol, int i, int j, int value)
  57. {
  58.     int q,t;
  59.    
  60.     if(i>=*numOfRow)    //if we need to add rows
  61.     {
  62.         array=(int**)realloc(array,(i+1)*sizeof(int*));
  63.        
  64.         for(q=*numOfRow;q<i+1;q++)
  65.             array[q]=(int*)calloc(*numOfCol,sizeof(int));
  66.            
  67.         *numOfRow=i+1;
  68.     }
  69.    
  70.  
  71.     if(j>=*numOfCol)    //if we need to add columns
  72.     {
  73.         for(q=0;q<*numOfRow;q++)
  74.         {
  75.             array[q]=(int*)realloc(array[q],(j+1)*sizeof(int));
  76.             for(t=*numOfCol;t<=j;t++)
  77.                 array[q][t]=0;
  78.         }
  79.         *numOfCol=j+1;
  80.     }
  81.    
  82.     array[i][j]=value;
  83.    
  84.     return array;
  85. }
  86.  
  87. int main ()
  88. {
  89.     int** arr=init_2darray(3,3);
  90.     int rows[1]={3};
  91.     int cols[1]={3};
  92.    
  93.     print_2darray(arr,*rows,*cols);
  94.  
  95.     printf("\n=======================================\n");
  96.  
  97.     arr=add_to_2darray(arr,rows,cols,5,5,7);
  98.     arr[2][0]=5;
  99.  
  100.     print_2darray(arr,*rows,*cols);
  101.     free_2darray(arr,*rows);
  102.     return 0;
  103. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement