#include <stdio.h>
#include <string.h>
typedef struct birth{
char *name;
char time[12];
}birth;
void swap(struct birth *a, struct birth *b){
struct birth tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
int main(){
int n;
birth list[100], *p, *q;
scanf("%d", &n);
getchar();
for(p = list; p < list n; p ){
scanf("%s %s", &p->name, &p->time);
}
for(p = list; p < list n - 1; p ){
for(q = p 1; q < list n; q ){
if(strcmp(p->time, q->time) > 0){
swap(p ,q);
}
else if(strcmp(p->time, q->time) == 0){
if(strcmp(p->name, q->name) > 0){
swap(p ,q);
}
}
}
}
for(int i = 0; i < n; i ){
printf("%s %s\n", list[i].name, list[i].time);
}
return 0;
}
I am solving the problem of receiving n, which means the number of students, repeating the number of students, receiving the student's name and date of birth, and printing the names in advance if the date of birth is the same. However, there was no answer, so I checked using the debugger in vcode, and when I received the input, the date of birth was well entered, but the name was not.
CodePudding user response:
birth list[100], *p, *q;
...
for(p = list; p < list n; p ){
scanf("%s %s", &p->name, &p->time);
}
Here you ask scanf to save data to &p->name
and you do not allocate space for p->name
.
CodePudding user response:
You are trying to read a string using a char pointer that was never initialized.
typedef struct birth{
char *name;
char time[12];
}birth;
...
scanf("%s %s", &p->name, &p->time); // error, &p->name points to nowhere
You should either allocate memory yourself or declare it as a fixed size char array. It would be best to check the string boundaries too:
#define S_NAME 12
#define S_TIME 12
typedef struct birth{
char name[S_NAME];
char time[S_TIME];
}birth;
...
// read string with safety guard
if (fgets(p->name, S_NAME, stdin) != NULL) {
// read name successfully
}
if (fgets(p->time, S_TIME, stdin) != NULL) {
// read time successfully
}