I'm trying to allocate memory to a matrix in a function and then print its values.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void cria_ilhas(int** ilhas, int n){
int i, p;
ilhas = (int**) malloc(n*sizeof(int*));
for (i=0;i<n;i++){
ilhas[i] = (int*) malloc(n*sizeof(int));
for (p=0; p<n; p++)
ilhas[i][p] = 4;
}
printf("value %d\n",ilhas[0][0]);
}
void main(){
int n=5, i, j;
int **ilhas;
cria_ilhas(ilhas, n);
for(i=0; i<n; i++){
for(j=0;j<n;j++){
printf("%d ",ilhas[i][j]);
}
printf("\n");
}
}
But this is the output:
value 4
Segmentation fault
Why i'm having segmentation fault?
How can I use memset in this kind of matrix?
You’re doing it almost correctly. When you’re calling cria_ilhas
, you’re passing in the variable ilhas
, and expecting that when you change it inside of the function, that effects the variable in main
, too. Unfortunately, C doesn’t work that way.1
What you’ll want to do is remove the ilhas
parameter from cria_ilhas
and stop passing it in when you call it in main
. Then just declare ilhas
as a local variable in cria_ilhas
. To get the value back to main, you’ll need to return it from cria_ilhas
, and in main
, when you call it, assign ilhas
to its result.
1 Side note: if you were using C++, you could make it work by changing the parameter from int **ilhas
to int **&ilhas
.