簡體   English   中英

為什么我在嘗試運行 find function 即使正確訪問 memory 時遇到分段錯誤?

[英]Why I am getting segmentation fault when trying to run the find function even though accessing memory properly?

發現 function 在程序中不工作。 我認為這是因為我的編譯器顯示的分段錯誤,但我無法理解為什么? 因為我正確使用了 memory。 如果不是因為分段錯誤,那么為什么我沒有得到我想要的 output,即使我沒有收到任何錯誤。

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

void find(int **p) {
    int small,large,i,j;
    small=large=p[i][j];
    for(i=0; i<3; i++) {
        for(j=0; j<3; j++) {
            if(small>p[i][j])
                small=p[i][j];
            else if(large<p[i][j])
                large=p[i][j];
        }
    }
    printf("\nSmallest : %d\nLargest : %d",small,large);
}

int main() {
    int **p;
    p=(int **)malloc(sizeof(int)*3);
    if(p==NULL) {
        printf("Unable to allocate memory.");
        exit(1);
    }
    int i;
    for(i=0; i<3; i++) {
        *(p+i)=(int *)malloc(sizeof(int)*3);
    }
    int j;
    for(i=0; i<3; i++) {
        for(j=0; j<3; j++)
            scanf("%d",(*(p+i)+j));
    }
    for(i=0; i<3; i++) {
        for(j=0; j<3; j++)
            printf("\nValue of [%d][%d] : %d",i,j,*(*(p+i)+j));
    }
    find(p);
    free(p);
    return 0;
}

有一個錯字

p=(int **)malloc(sizeof(int)*3);
                        ^^^   

看來你的意思

p=(int **)malloc(sizeof(int *)*3);
                        ^^^^^

除了這個 memory 釋放

free(p);

您還需要釋放每個分配的數組,例如

for ( i = 0; i < 3; i++ )
{
    free( *( p + i ) );
}

free( p );

在 function 中find您正在使用未初始化的變量ij

void find(int **p) {
    int small,large,i,j;
    small=large=p[i][j];
    //...

你需要初始化它們

void find(int **p) {
    int small,large,i = 0,j = 0;
    small=large=p[i][j];
    //...

雖然至少寫起來會更簡單

void find(int **p) {
    int small = p[0][0], large = p[0][0];

    for ( int i = 0; i < 3; i++ )
    //...

暫無
暫無

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

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