简体   繁体   English

C阵列程序因分段错误而崩溃

[英]C Array program is crashing with segmentation fault

I am learning array and just wrote this small program to see how it works. 我正在学习数组,只是写了这个小程序,看它是如何工作的。 but its crashing with segmentation faul which i understand mean i am writing my variable / function to an memory place not allotted to it. 但它崩溃了我理解的分段faul意味着我正在将我的变量/函数写入一个没有分配给它的内存位置。 But I cant figure how. 但我不知道如何。 Can anyone let me know please? 有人能告诉我吗? i am calling introArray from my main(). 我从main()调用introArray。

int introArray (void)
{
    int total, ctr;

    printf("enter how many students \n");
    scanf("%d", &total);

    int students[total];
    ctr = 0;

    while ( students[ctr] <= total)
    {
        printf("enter student %d DOB in mmddyy \n", ctr );
        scanf("%d", students[ctr]);
        ctr++;
    }

    return 0;

} }

In your code, there is one implementation logic issue. 在您的代码中,存在一个实现逻辑问题。 The total number of students is total and hence, your while loop should be 学生totaltotal ,因此,你的while循环应该是

while(ctr < total)

The data to be read also should scanf("%d", &students[ctr]); 要读取的数据也应该是scanf("%d", &students[ctr]); There is an ampersand missing 有一个&符号丢失

ctr goes beyond total . ctr超越了total This way you are going out of bound Change the loop to 通过这种方式,您可以将循环更改为

while (ctr < total)
{
        printf("enter student %d DOB in mmddyy \n", ctr );
        scanf("%d", &(students[ctr]));
        ctr++;
}

This line 这条线

while ( students[ctr] <= total)

is not protection against reading past your array bounds inside the loop. 不能防止读取循环内的数组边界。 This will stop you reading past the end of your array provided you use ctr as your index 如果您使用ctr作为索引,这将阻止您读取数组的末尾

while ( ctr < total)

you need the strict inequality as array indices are zero based. 你需要严格的不等式,因为数组索引是零基础的。

In addition, your scanf call inside your while loop is wrong - the second argument should be a pointer and currently you pass an integer. 另外,你的while循环中的scanf调用是错误的 - 第二个参数应该是一个指针,目前你传递一个整数。 It should be 它应该是

scanf("%d", &students[ctr]);

I think 我认为

scanf("%d", students[ctr]);

should be 应该

scanf("%d", &students[ctr]);

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

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