Reputation: 1229
Hello I have this struct below :
typedef struct GRAPHE{
int n; /* Nombre de sommets */
int **M; /* Matrice d'Adjacence */
} GRAPHE;
I need to allocate memory ,I tried this function but it doesn't seem to work
void reservation_en_memoire(int n, GRAPHE *g) {
int i, j;
g = (GRAPHE *) malloc(n * sizeof (struct GRAPHE));
g->M = (int **) malloc(n * sizeof (int*));
for (i = 0; i < n; i++)
g->M[i][j] = (int) malloc(n * sizeof (int));
g->n = n;
}
And in the main I'm just doing like this :
int main(int argc, char** argv) {
GRAPHE *g;
reservation_en_memoire(3, g);
printf("%d", g->n);
// printf("%d", g->M[0][0]);
return (EXIT_SUCCESS);
}
Can you please give me a little help here please !!
Upvotes: 1
Views: 489
Reputation: 16153
There are several problems I see:
j
is uninitializedM
is supposed to be per-instance of GRAPHE
, your code will not workg
= ... malloc( n * ... )
is allocating n
copies of GRAPHE
, which you then access as g->(struct_member)
. g
points to an array after a successful call to malloc
. You should be accessing it as g[index]
if an array was truly your intent.reservation_en_memoire
completes so you'll never see the result of reservation_en_memoire
reflected in main
That should be enough to get you on the right track...
Upvotes: 0
Reputation: 409374
You have a beginners mistake here, in that you pass the pointer g
from main
by-value. That means that in the reservation_en_memoire
function you are only allocating memory to a copy of the pointer, a copy which disappears when the function returns (but the memory the pointer points to will not be unallocated, so you have a memory leak). When you then access g
in the main
function, it's still the uninitialized pointer you declared there, and you have undefined behavior.
To make it work you have to pass the pointer by reference, i.e. as a pointer to the pointer.
void reservation_en_memoire(int n, GRAPHE **g) {
*g = malloc(sizeof (GRAPHE));
(*g)->M = malloc(n * sizeof (int*));
for (int i = 0; i < n; i++)
(*g)->M[i] = malloc(n * sizeof (int));
(*g)->n = n;
}
And call it using the address-of operator &
:
GRAPHE *g;
reservation_en_memoire(3, &g);
As you can see I have made some substantial changes to your reservation_en_memoire
function, except the ones needed by passing the pointer by reference. The first is that I only allocate one GRAPHE
structure instead of n
structures. The second is that in the loop I no longer index the second dimension of the matrix, as it's what's being allocated in the loop.
Upvotes: 5