簡體   English   中英

使用此代碼出現分段錯誤,但我不知道如何修復它

[英]Getting segmentation fault with this code but I'm not sure how to fix it

當我嘗試使用以下數字運行程序時,我在這里遇到分段錯誤:

17 56
2748 55539 ​​24890 4564
1995 44437 39060 75810
2583 49463 73827 24420
395 46500 56779 60559
273 30090 78489 37881
950 76442 92020 15157
756 85200 19627 13615
1787 79756 51484 34462
1424 65520 83527 74748
2738 10501 9678 95956
2250 92554 55640 91863
2402 84001 72097 92122
1223 71750 71493 12744
164 99321 73824 93276
1057 96262 24703 68502
1649 76765 48873 18181
2552 49371 32960 81865

我有一種感覺,它可能必須對 scanf 做一些事情,但我不確定它是什么。

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

int main(){
        int holes;
        int p;
        scanf("%d %d", &holes, &p);
        double plates = (double) p;
        int* R[holes];
        int* X[holes];
        int* Y[holes];
        int* Z[holes];
        double sizeOfPlate[p];
        for(int i = 0; i < holes; i++){
                scanf("%d %d %d %d", R[i], X[i], Y[i], Z[i]);
        }

        if(holes == 0){
                for(int i = 0; i < p; i++){
                        sizeOfPlate[i] = 100 / plates;
                }
                for (int i = 0; i < p; ++i)
                {
                        printf("%.9lf\n", sizeOfPlate[i]);
                }
        }
        else if(p == 1)
                printf("100.0000000");
        else{
                printf("Wrong result");
        }
        return 0;
}

在您的代碼中,

    int* R[holes];
    int* X[holes];
    int* Y[holes];
    int* Z[holes];

都是指針數組,但就其本身而言,這些指針並不指向任何有效內存。 除非這些數組中的每個指針都指向有效內存,否則將它們用作scanf()參數將導致未定義行為 分段錯誤是副作用之一。

你需要要么

  • 將這些指針指向一些有效的內存(使用malloc()等分配器函數)
  • 制作類型為int而不是int *的數組,然后使用每個元素的地址作為scanf()參數。

暫無
暫無

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

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