我对编程很陌生,这是大学作业。我不知道是什么导致了这个分段错误,请帮忙。
#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](;
如果 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]);
}
}