简体   繁体   English

使用此代码出现分段错误,但我不知道如何修复它

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

I'm getting segmentation fault here when I try to run the program with for example these numbers:当我尝试使用以下数字运行程序时,我在这里遇到分段错误:

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

I have a feeling it may have to do something with scanf but I'm not sure what it is.我有一种感觉,它可能必须对 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;
}

In your code,在您的代码中,

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

all are arrays of pointers, but in itself, these pointers do not point to any valid memory.都是指针数组,但就其本身而言,这些指针并不指向任何有效内存。 Unless a valid memory is pointed to by each of these pointers in these arrays, using them as argument to scanf() will lead to undefined behaviour .除非这些数组中的每个指针都指向有效内存,否则将它们用作scanf()参数将导致未定义行为 Segmentation fault is one of the side effects.分段错误是副作用之一。

You need to either你需要要么

  • point these pointers to some valid memory (sing allocator function like malloc() )将这些指针指向一些有效的内存(使用malloc()等分配器函数)
  • make the arrays of type int instead of int * and then use the address of each element as argument to scanf() .制作类型为int而不是int *的数组,然后使用每个元素的地址作为scanf()参数。

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

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