Taking in unique inputs in a struct array in C -
i writing program create structure named 'student'. need input various data particular student. here program till now.
#include<stdio.h> #include<stdlib.h> struct student { char* name; int id; float marks_1; float marks_2; }; void main() { int num, var_i, var_j, var_k, var_l, duplicated_id = 0; printf("enter number of students\n"); scanf("%d", &num); struct student s[num]; printf("enter data students\n"); (var_i = 0; var_i < num; var_i++) { var_j = var_i + 1; printf("enter name of student_%d\n", var_j); scanf(" %[^\n]%*c", &s[var_i].name); printf("enter id of student_%d\n", var_j); scanf("%d", &s[var_i].id); (var_k = 0; var_k < var_i; var_k++) { if (s[var_k].id == s[var_i].id) { printf("duplicate id, program exit"); return; } } printf("enter marks(sub_1) of student_%d\n", var_j); scanf("%d", &s[var_i].marks_1); printf("enter marks(sub_2) of student_%d\n", var_j); scanf("%d", &s[var_i].marks_2); } }
in following loop checking entered 'id' values check if there duplicate. in case of duplicate, program exit.
for(var_k=0;var_k<var_i;var_k++) { if(s[var_k].id==s[var_i].id) { printf("duplicate id, program exit"); return; } }
now instead of exiting program want prompt user enter different value. goes on till enters unique value. how should it? appreciated.
this wrong:
scanf(" %[^\n]%*c", &s[var_i].name);
you're passing address of pointer member name
(i.e. you're passing char **
) scanf()
per format string, expecting char*
, enough memory hold data subsequently reads. invalid, undefined behavior, , blindly overwrites data in s[]
array. frankly i'm amazed doesn't seg-fault process.
change this:
struct student { char* name; int id; float marks_1; float marks_2; };
to this:
struct student { char name[128]; // or other suitable size. int id; float marks_1; float marks_2; };
and change this:
scanf(" %[^\n]%*c", &s[var_i].name);
to this:
scanf(" %[^\n]%*c", s[var_i].name);
i suggest size-limiter on scanf()
call well, leave discover. read api here.
Comments
Post a Comment