I'am trying to figure out what's wrong with my code.When compiling, no errors or warning, just a segmentation fault.
Can someone tell me what am i doing wrong??
#include "funciones.h"
#define FILAS 5
#define COLUMNAS 3
#define VALOR 2
int main(void)
{
int estado;
int **matriz = NULL;
estado = generar_matriz(FILAS,COLUMNAS, 2, matriz);
if(estado == OK)
{
printf("matriz creada exitosamente \n");
}
else
printf("error en el creado de la matriz \n");
return 0;
}
#ifndef FUNCIONES_H_
#define FUNCIONES_H_
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ERROR -1
#define OK 0
int generar_matriz(int filas, int columnas, int valor, int** matriz);
#endif
#include "funciones.h"
int generar_matriz(int filas, int columnas, int valor, int** matriz)
{
int estado = OK,i,j;
if(filas != 0 && columnas != 0)
{
matriz = (int**)malloc(sizeof(int*)*filas);
if(matriz != NULL)
{
for(i = 0;i<filas;i++)
{
matriz[i] = (int*)malloc(sizeof(int)*columnas);
if(matriz[i] == NULL)
estado = ERROR;
else
{
for(j = 0;j<columnas;j++)
*(matriz[j]) = valor;
}
}
}
else
estado = ERROR;
}
else
estado = ERROR;
return estado;
}
`
I think the logic is pretty clear. The first malloc call is to allocate an array of int pointers, and then i use a for function to ask for memory and fill each 4 bytes with the number that the function recived. I also would accept better code practices and tips. Thank you.
int generar_matriz(int filas, int columnas, int valor, int** matriz), the value passed in formatrizis not used, nor is the original data pointed to bymatrizchanged. Was that intended?