代码之家  ›  专栏  ›  技术社区  ›  Misael Indra Wijaya

数组c上的分段错误

  •  1
  • Misael Indra Wijaya  · 技术社区  · 8 年前

    我对编程很陌生,这是一项大学作业。我不知道是什么导致了这个分段错误,请帮助。

    #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 回复  |  直到 8 年前
        1
  •  0
  •   Bwebb    8 年前

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

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

    因此,如果您的输入是“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]);
        }
    }