简体   繁体   English

数组c上的分割错误

[英]segmentation fault on array c

I am pretty new to programming and this is a college assignment. 我对编程很陌生,这是大学的工作。 I don't know what is causing this segmentation fault, please help. 我不知道是什么导致此细分错误,请提供帮助。

#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]);
    }
}

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

if nama is a char array, the format specifier you want is %c instead of %s. 如果nama是一个char数组,则所需的格式说明符为%c而不是%s。 %s is for string which will try to write all of the input string (up to the nul terminator) into your char array. %s是字符串,它将尝试将所有输入字符串(直到nul终止符)写入char数组。

So, if your input was "This Will Segfault" you would have (even from your first loop in the for loop) 因此,如果您输入的是“ 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.

if you want an array of strings instead of an array of chars you need to change you struct to something like this: 如果您想要一个字符串数组而不是一个字符数组,则需要将结构更改为以下形式:

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]);
    }
}

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

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