648trindade
648trindade

Reputation: 748

Problems with allocating memory for a matrix in c

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?

Upvotes: 2

Views: 92

Answers (2)

Iman Rosstin
Iman Rosstin

Reputation: 2355

Change your code to this shape and tell me if it worked

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int** cria_ilhas( int n){
    int i, p;
    int **ilhas
    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]);
    return ilhas;
}
void main(){
    int n=5, i, j;
    int **ilhas;
    ilhas = cria_ilhas(n);
    for(i=0; i<n; i++){
        for(j=0;j<n;j++){
            printf("%d ",ilhas[i][j]);
        }
        printf("\n");
    }   
}

I think it should work for you, your code is much likely to be true but the problem is you have defined a large structure in heap (ilhas definition in main method) and you sent it address to a method ( call by reference) which suppose to allocate memory for it from stack segment but not heap, if you pass the address of a simple type variable to a method, it woundnt be a problem but allocating memory for array's will raise segmentation problem.

Upvotes: 1

icktoofay
icktoofay

Reputation: 129011

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.

Upvotes: 2

Related Questions