簡體   English   中英

嘗試 malloc 結構指針時出錯

[英]Error when trying to malloc a struct pointer

我試圖在 C 中定義兩個二維矩陣,但程序在創建第二個后崩潰。

我究竟做錯了什么?

我懷疑這可能是我從函數返回 Matrix 的方式,但如果有人能指導我,那就太好了,謝謝。

#include <stdio.h>
#include <stdlib.h>

struct Matriz{
    int m;
    int n;
    int **mat;
};
struct Matriz getMatriz(int index){
    int m, n;
    printf("Input row number for matrix %d: ", index);
    scanf("%d",&m);
    printf("Input column number for matrix %d: ", index);
    scanf("%d",&n);
    struct Matriz *matriz = malloc(sizeof(struct Matriz));  //after this the program crashes
    matriz->m=m;
    matriz->n=n;
    matriz->mat=malloc(m*n*sizeof(int));
    //struct Matriz matriz = {m, n, malloc(m*n*sizeof(int))};
    for(int i=0; i<m; i++)
        for(int j=0; j<n; j++){
            printf("Input row %d, column %d: ", i+1, j+1);
            scanf("%d", &matriz->mat[i][j]);
            printf("input: %d\n", matriz->mat[i][j]);
        }
    fputs("\n", stdout);
    return *matriz;
}
int main(){
    struct Matriz matriz1 = getMatriz(1);
    printf("size1 %d %d\n", matriz1.m, matriz1.n);
    struct Matriz matriz2 = getMatriz(2);  //Cannot create the second matrix
    printf("size2 %d %d\n", matriz2.m, matriz2.n);
    for(int i=0; i<matriz1.m; i++)
        for(int j=0; j<matriz1.n; j++)
            printf("%d", matriz1.mat[i][j]);
        fputs("\n\n", stdout);
    }
    return 0;
}

int **mat是指向 int 的指針數組的聲明。

malloc(m * n * sizeof(int))不分配指針數組,而是分配一維整數數組。

分配矩陣的正確方法是:

matriz->mat = malloc(m * sizeof(int*));
for (int i = 0; i < m; i++) {
    matriz->mat[i] = malloc(n * sizeof(int));
}
struct Matriz *matriz = (struct Matriz*)malloc(sizeof(struct Matriz));

如果您使用的是 C++ 編譯器,您應該使用類型轉換來返回malloc()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM