簡體   English   中英

有人可以解釋為什么我的程序崩潰嗎?

[英]Can someone please explain why my program crashes?

我在編譯時沒有任何錯誤。 該程序只是在我運行時崩潰。 我嘗試直接從generate函數打印矩陣,並打印了第一行和第二行。

這是我的代碼

void generate(int **a)//*Function to generate a matrix a[i][j]=i+j*
{
    int i,j;
    for(i=0;i<5;i++){
        for(j=0;j<4;j++){
            a[i][j]=i+j;
        }
    }
}

void print(int **a)//*print the resulting matrix from generate function*
{
    int i,j;
    for(i=0;i<5;i++){
        for(j=0;j<4;j++){
            printf("%d ",a[i][j]);
        }
        printf("\n");
    }
}

int main()
{
    int *a=(int*)malloc(5*4*sizeof(int));//*allocating memory for a matrix of 4 lines and 5 columns.*
    generate(&a);
    print(&a);
}

1)您正在分配一個維度存儲器。

a[i][j]=i+j; //is not valid.

下面是修改后的代碼

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

void generate(int *a)//*Function to generate a matrix a[i][j]=i+j*
{
    int i,j;
    for(i=0;i<5;i++){
        for(j=0;j<4;j++){
            *a=i+j;
                a++; //increments to next memory location
        }
    }
}

void print(int *a)//*print the resulting matrix from generate function*
{
    int i,j;
    for(i=0;i<5;i++){
        for(j=0;j<4;j++){
            printf("%d ",*(a++)); //notice another way of accessing 
        }
        printf("\n");
    }
}

int main()
{
    int *a=(int*)malloc(5*4*sizeof(int));//*allocating memory for a matrix of 4 lines and 5 columns.*
    generate(a);
    print(a); //passing the pointer
    free(a); //Always always practice to free the allocated memory, don't ever do this mistake again
    return 0;
}

兩件事情:

首先, int **表示指向一個指向int **的指針的指針,而不是指向一個int數組的指針。

其次,當您僅將指針傳遞到某個數據結構(例如4x5整數數組)時,編譯器將無法得出此數據結構的布局。 即,像a[i][j]這樣的語句將要求編譯器“知道”每行i由4列j ,這樣它就可以計算應將值存儲到的“位置”,即a + (4*i) + j 編譯器根本不知道每行的列數nr,即4

要克服此問題,同時使數組的大小至少保持潛在的可變性(請注意,函數中仍對硬編碼“ 4”和“ 5”),可以執行以下操作:

void generate(int *a)//*Function to generate a matrix a[i][j]=i+j*
{
    int i,j;
    for(i=0;i<5;i++){
        for(j=0;j<4;j++){
            *(a+(i*4+j)) = i+j;
        }
    }
}

void print(int *a)//*print the resulting matrix from generate function*
{
    int i,j;
    for(i=0;i<5;i++){
        for(j=0;j<4;j++){
            printf("%d ", *(a+(i*4+j)));
        }
        printf("\n");
    }
}

int main()
{
    int *a=(int*)malloc(5*4*sizeof(int));//*allocating memory for a matrix of 4 lines and 5 columns.*
    generate(a);
    print(a);
}

暫無
暫無

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

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