Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <stdio.h>
- /*
- *Name: Tomer Kopf Adar
- *ID: 304821952
- */
- // allocates a dynamic 2d array (array of arrays)
- int** init_2darray(int numOfRow, int numOfCol) {
- int i, j;
- int** array = (int**) malloc (sizeof(int*)*numOfRow);
- if (array==NULL)
- return NULL;
- for (i=0;i<numOfRow;i++) {
- array[i] = (int*) calloc (numOfCol,sizeof(int));
- if (array[i]==NULL) {
- for (j=0;j<i;j++)
- free(array[j]);
- free(array);
- return NULL;
- }
- }
- return array;
- }
- // frees a dynamic 2d array
- void free_2darray(int** array, int numOfRow) {
- int i;
- for (i=0;i<numOfRow;i++)
- free(array[i]);
- free(array);
- }
- // prints a 2d array
- void print_2darray(int** array, int numOfRow, int numOfCol) {
- int i, j;
- for (i=0;i<numOfRow;i++) {
- for (j=0;j<numOfCol;j++)
- printf("%10d",array[i][j]);
- printf("\n");
- }
- }
- // modifies a value of a 2d array
- // if index is out of current bounds, extends the array to the minimum required size
- int** add_to_2darray(int** array, int* numOfRow, int* numOfCol, int i, int j, int value)
- {
- int q,t;
- if(i>=*numOfRow) //if we need to add rows
- {
- array=(int**)realloc(array,(i+1)*sizeof(int*));
- for(q=*numOfRow;q<i+1;q++)
- array[q]=(int*)calloc(*numOfCol,sizeof(int));
- *numOfRow=i+1;
- }
- if(j>=*numOfCol) //if we need to add columns
- {
- for(q=0;q<*numOfRow;q++)
- {
- array[q]=(int*)realloc(array[q],(j+1)*sizeof(int));
- for(t=*numOfCol;t<=j;t++)
- array[q][t]=0;
- }
- *numOfCol=j+1;
- }
- array[i][j]=value;
- return array;
- }
- int main ()
- {
- int** arr=init_2darray(3,3);
- int rows[1]={3};
- int cols[1]={3};
- print_2darray(arr,*rows,*cols);
- printf("\n=======================================\n");
- arr=add_to_2darray(arr,rows,cols,5,5,7);
- arr[2][0]=5;
- print_2darray(arr,*rows,*cols);
- free_2darray(arr,*rows);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement