#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
void print(int **array,int row,int col){
int i,j;
for(i=0;i<row;++i){
for(j=0;j<col;++j){
printf("%d ",array[i][j]);
}
printf("\n");
}
}
int **take(int *row,int *col){
int i; int **array;
printf("Enter the row number for array \n");
scanf("%d",row);
printf("Enter the column number for the array \n");
scanf("%d",col);
array=(int**)malloc(sizeof(int*)*(*row));
for(i=0;i<(*row);++i){
array[i]=(int*)malloc(sizeof(int)*(*col));
}
return array;
}
void assign(int **array,int row,int col){
int i,j;
srand(time(NULL));
for(i=0;i<row;++i){
for(j=0;j<col;++j){
array[i][j]=rand()%50;
}
}
}
int **increase(int **array,int *row,int *col){
int **temp;int trow=*row;int tcol=*col;
temp=take(row,col);
memcpy(temp,array,sizeof(int)*trow*tcol);
free(array);
return temp;
}
int main(){
int **array=NULL; int row,col;
array=take(&row,&col);
assign(array,row,col);
print(array,row,col);
array=increase(array,&row,&col);
array[2][0] = 1;
free(array);
return 0;
}
First ı am making 2 by 3 matrix and print it then increase it 3 by 4 and when trying to reach array[2][0], I am taking segmentation fault What is the problem.I checked it many times but I could not find anything
Rather than
memcpy
,realloc
could be used to increase the size ofarray
. Check the return of realloc and malloc as they can fail.The return of scanf should also be checked as it can fail as well.
Instead of scanf, this uses fgets for input and parses the input with strtol in the
get_int_range
function.Using realloc allows the
take
andincrease
functions to be combined. Since thetake
function now has knowledge of the old and new sizes, the operation of theassign
function can also be included.takeaway
handles freeing the allocated memory.