I am writing a C program that lists students and adds students, but when I add a new student, although I can read the value successfully, the function can only print the first 2 elements to the screen and cannot read the newly added ones properly.
code is here:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
typedef char str[50];
typedef struct{
str name;
str surname;
int year;
int no;
}Student;
void list(Student[2],int sn);
int main() {
Student students[100] = {
{"samuel","any",20,111},
{"veronica","suqal",25,87}
};
int sl = 2;
puts("list, add, exit");
puts("------------------------n");
str process;
while(strcmp(process,"exit")) {
gets(process);
if(!strcmp(process,"list")) list(students,sl);
else
if(!strcmp(process,"add")) {
sl++;
str name,surname,year,no;
printf("n name: ");
gets(name);
printf("n surname: ");
gets(surname);
printf("n year: ");
gets(year);
printf("n no: ");
gets(no);
strcpy(students[sl].name,name);
strcpy(students[sl].surname,surname);
students[sl].no = atoi(no);
students[sl].year = atoi(year);
printf("%s %d",name,atoi(no));
} else if(!strcmp(process,"exit")) {
puts("-------exiting--------");
}
else
{
str out = "not known command: ";
strcat(out,process);
puts(out);
}
}
return 0;
};
void list(Student* students,int sn) {
for(int i=0;i<sn;i++)
{
Student std = students[i];
printf("student: n name: %s, surname: %s, years: %d, no: %d n",std.name,std.surname,std.year,std.no);
}
};
When I add a new element, I can read it on the screen with printf, but when I list it with the function, this happens:
list, add, exit
------------------------
add
name: hello
surname: world
year: 1
no: 1
hello 1
list
student:
name: samuel, surname: any, years: 20, no: 111
student:
name: veronica, surname: suqal, years: 25, no: 87
student:
name: , surname: , years: 0, no: 0
Emmet is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2
The first element of an array is at index 0.
Here, you increment “sl” variable before storing variables in your array, which means that :
- When you try to save the data for the third student, sl il equals to 3, so this student will be stored in the fourth element of your array
you’re incrementing sl before adding the new student data, which causes you to write to an index that is off by one.
put sl++; in the end of the if(!strcmp(process,”add”)) statement not at the top
Mustapha Moukit is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.