简体   繁体   English

访问结构中的双指针

[英]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.您为A.jumlahBaris * A.jumlahKolom未初始化的指针分配了一个内存段。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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