簡體   English   中英

scanf 出現分段錯誤(核心轉儲)

[英]Segmentation fault (core dump) with scanf

我編寫了一個簡單的程序來獲取用戶的姓名和數字並將其存儲在一個數組中,然后在每個單元格之間進行比較,直到達到最高等級,然后將其顯示出來。 問題是它在運行時會顯示一條消息(分段錯誤(核心轉儲))。 我真的不知道我的錯誤是什么。

#include <stdio.h>

int main() {
    int n;
    printf("Enter the number of students: ");
    scanf("%d", & n);
    char name[n];
    float score[n];
    for (int i = 0; i < n; i++) {
        printf("\nEnter the name of Student: ");
        scanf("%s", & name[i]);
        printf("\nEnter the score:  ");
        scanf("%f", & score[i]);
    }
    float max;
    int index;
    max = score[0];
    index = 0;
    for (int i = 1; i < n; i++) {
        if (max < score[i]) {
            max = score[i];
            index = i;
        }
    }
    printf("\nHighest mark scored is %f by student %s", name[index], score[index]);
}
1- you use user input to define the size of an array (wrong)
-- array in c has static size so you must define it's size before the code reach the compiling stage(use dynamic memory allocation instead)
2- scanf("%s", & name[I]); you want  to save array of char and save the address at the name variable but name it self not a pointer to save address it's just of char type  (wrong)
-- you need pointer to save the address of every name so it's array of pointer and a pointer to allocate the address of the array to it so it's  a pointer to poiner and define max size of word if you define size the user input exceed it will produce an error
3- finally you exchanged the %f,%s in printf 





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

    #define SIZE_OF_WORD 10

    int main() {
        int n;
    printf("Enter the number of students: ");
    scanf("%d", & n);
    char **name=(char**)malloc((sizeof(char*)*n));
    for (int i = 0; i < n; i++) {
        name[i]=(char*)malloc((sizeof(char)*SIZE_OF_WORD));
    }
    float *score=(float*)malloc((sizeof(float)*n));
    for (int i = 0; i < n; i++) {
        printf("\nEnter the name of Student: ");
        scanf("%s", name[i]);
        printf("\nEnter the score:  ");
        scanf("%f", & score[i]);
    }
    float max;
    int index;
    max = score[0];
    index = 0;
    for (int i = 1; i < n; i++) {
        if (max < score[i]) {
            max = score[i];
            index = i;
        }
    }
    printf("\nHighest mark scored is %s by student %.0f\n", name[index],score[index]);
}

暫無
暫無

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

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