简体   繁体   中英

Accessing double pointer in a struct

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.

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 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM