阵列c上的分段错误

时间:2018-05-01 01:05:03

标签: c segmentation-fault

我对编程很陌生,这是一项大学任务。我不知道造成这种分段错误的原因,请帮助。

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

main() {
    int i, n;

    struct obat {
        char nama[10];
        char kode[10];
        int harga[10];
        int stok[10];
    };

    struct obat o;

    printf("Masukan jumlah obat = ");

    scanf("%d", &n);

    for (i = 0; i < n; i++) {
        printf("Masukan nama obat ke-%d", i + 1);
        scanf("%s", &o.nama[i]);
    }

    for (i = 0; i < n; i++) {
        printf("Nama obat ke-%d = %s", i + 1, o.nama[i]);
    }
}

1 个答案:

答案 0 :(得分:0)

scanf(“%s”,&amp; o.nama [i]);

如果nama是一个char数组,你想要的格式说明符是%c而不是%s。 %s用于字符串,它将尝试将所有输入字符串(直到nul终止符)写入char数组。

所以,如果您输入的是“This Will Segfault”,那么(即使是for循环中的第一个循环)

o.nama[0] = T
o.nama[1] = h
o.nama[2] = i
o.nama[3] = s
o.nama[4] = "space" (not the word but the symbol)
o.nama[5] = W
o.nama[6] = i
o.nama[7] = l
o.nama[8] = l
o.nama[9] = "space" (again)
o.nama[10] = S //This is the seg fault most likely, although it may also write into other parts of your struct unintentionally.

如果你想要一个字符串数组而不是一个字符数组,你需要将结构改为这样的结构:

main() {
    int i, n;

    struct obat {
        char nama[10][512]; //the 512 here should be #defined
        char kode[10];
        int harga[10];
        int stok[10];
    };

    struct obat o;
    memset(o, 0, sizeof(stuct obat)); //set your struct to 0 values, important for strings.

    printf("Masukan jumlah obat = ");

    scanf("%d", &n);

    for (i = 0; i < n; i++) { //loops over at most 10 inputs and reads the input string
        printf("Masukan nama obat ke-%d", i + 1);
        scanf("%s", &o.nama[i][0]);
    }

    for (i = 0; i < n; i++) {
        printf("Nama obat ke-%d = %s", i + 1, o.nama[i][0]);
    }
}