Reputation: 11
It's not giving any output. It's look like i dont really undestand how to access double pointer in a struct.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct Matriks{
int jumlahBaris;
int jumlahKolom;
int** nilai;
} Matriks, *Matriks2;
void main(){
int i;
int baris = 0;
int kolom = 0;
Matriks A;
A.jumlahBaris = 2;
A.jumlahKolom = 3;
A.nilai = (int **)malloc((A.jumlahBaris)*(A.jumlahKolom)*sizeof(int*));
Matriks2 pA = &A;
int x = 26;
int y = 12;
A.nilai[0][0] = x;
A.nilai[0][2] = y;
printf("%d\n", A.nilai[0][0]);
printf("%d", A.nilai[0][2]);
free(A.nilai);
}
Please help me to know what is wrong with my code.
Upvotes: 1
Views: 71
Reputation: 310980
This memory allocation
A.nilai = (int **)malloc((A.jumlahBaris)*(A.jumlahKolom)*sizeof(int*));
is invalid.
You allocated a memory segment for A.jumlahBaris * A.jumlahKolom
uninitialized pointers.
What you need is the following
A.nilai = malloc( A.jumlahBaris * sizeof( int* ) );
for ( int i = 0; i < A.jumlahBaris; i++ )
{
A.nilai[i] = malloc( A.jumlahKolom * sizeof( int ) );
}
So correspondingly the allocated memory should be freed in the reverse order
for ( int i = 0; i < A.jumlahBaris; i++ )
{
free( A.nilai[i] );
}
free( A.nilai );
Upvotes: 2