Crashea program when using scanf on float matrix

1

I am learning to program in c. I'm looking at the topic of structures and pointers. The following program should create a structure with a pointer to pointer type float and save numbers in it. However, the captures crash when the number of rows is less than the number of columns. I can not find what the reason is. I appreciate any help or direction they could give me. Thanks.

#include <stdio.h>
#include <stdlib.h>

typedef struct matriz
{
    int filas;
    int columnas;
    float **array;
} Matriz;

float **creaMatriz(int, int);
Matriz captura();
void mostrar(Matriz*);
void libera(Matriz*);

int main(void)
{
    Matriz *A;
    Matriz *B;

    A = (Matriz*)calloc(1, sizeof(Matriz));
    B = (Matriz*)calloc(1, sizeof(Matriz));

    A[0] = captura();
    B[0] = captura();

    mostrar(A);
    mostrar(B);

    libera(A);
    libera(B);

    getchar()
    return 0;
}

float ** creaMatriz(int filas, int columnas)
{   
    int i;  
    float ** X = (float* *)calloc(filas, sizeof(float *));

    for (i = 0; i<columnas; i++)
        X[i] = (float *)calloc(columnas, sizeof(float));

    return X;
}

Matriz captura()
{
    int F = 0;
    int C = 0;
    int i = 0;
    int j = 0;

    Matriz X = {0,0,NULL};

    printf("Filas matriz:");
    scanf("%d", &F);
    printf("Columnas matriz:");
    scanf("%d", &C);

    X.array = creaMatriz(F, C);
    X.filas = F;
    X.columnas = C;

    for (i = 1; i<=X.filas; i++)
    {
        for (j = 1; j<=X.columnas; j++)
        {
            printf("Introdusca valor en posicion %d %d : ", i + 1, j + 1);
            scanf("%f", &X.array[i][j]);
        }
    }

    printf("\n");
    return X;
}

void mostrar(Matriz *AB)
{
    int i = 0;
    int j = 0;

    printf("\n");

    for (i = 0; i<AB[0].filas; i++)
    {
        for (j = 0; j<AB[0].columnas; j++)
        {
            printf("%.2f ", AB[0].array[i][j]);
        }
        printf("\n");
    }

    return;
}

void libera(Matriz *AB)
{
    int i;
    for (i = 0; i<AB[0].filas; i++)
    free(AB[0].array[i]);

    free(AB);
    return;
}
    
asked by user35102 02.04.2017 в 00:17
source

1 answer

3

If you create an array with, say, 10 elements, they will be available in the [0.9] range. So, if you indicate that the number of elements is 10, you can not ask yourself to iterate over the range [1,10] because then you will try to access memory that does not belong to you.

Your loops are incorrect:

for (i = 1; i<=X.filas; i++)

The correct thing would be (also applicable to the loop of j nested):

for (i = 0; i<X.filas; i++)

That is similar to what you are already applying in the mostrar function.

    
answered by 02.04.2017 / 02:26
source