Core dump using scanf in a function for arrays bigger than a certain length
Good morning guys
I have tried to write a function which allows to enter an array with scanf(). The array must be bidimensional, something like array[R][3] where R is a length decided by the user, 3 is the number of columns. To allocate memory for the array, I have to use malloc, and it seems to work fine. As you can see in the code below, which is not the final code but contains the function, the function must return the matrix created. So, for R values under 5, the program works. For R=5 and bigger, it returns "segmentation fault (core dump)", and I'd like to understand why this happens.
Code:
#include<stdlib.h>
#include<stdio.h>
float **MatriceInput(int R);
int main(void){
int i,R;
float **M;
printf("Enter the number of lines\n");
scanf("%d",&R);
M=MatriceInput(R);
for(i=0;i<R;i++){
printf("%f\t%f\t%f\n",**(M+i),*(*(M+i)+1),*(*(M+i)+2));
}
}
float **MatriceInput(int R){
int i,j;
float **A;
A=(float **)malloc(R*sizeof(float));
if(A==NULL){
printf("First malloc failed\n");
}
for(i=0;i<R;i++){
A[i]=(float *)malloc(3*sizeof(float));
if(A[i]==NULL){
printf("Second malloc failed\n");
}
}
for(j=0;j<3;j++){
printf("Enter the column %d\n",j+1);
for(i=0;i<R;i++){
scanf("%f",&*(*(A+i)+j));
}
}
return(A);
}