Reputation: 23
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]);
}
}
Upvotes: 1
Views: 109
Reputation: 685
scanf("%s", &o.nama[i]);
if nama is a char array, the format specifier you want is %c instead of %s. %s is for string which will try to write all of the input string (up to the nul terminator) into your char array.
So, if your input was "This Will Segfault" you would have (even from your first loop in the for loop)
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]);
}
}
Upvotes: 1