简体   繁体   中英

use printf and scanf on char *

I'm having problems inputting values into this structure template, please help. I've got to use char* for those attributes. so it doesn't give an error while inputting data but crashes when its time to display.

    #include<stdio.h>
#include<malloc.h>
#include<conio.h>
struct Date
{
  int day;
 char *month;
  int year;
}date;
struct sports_team
{
     char *name;
    char *city;
 int no_of_players;
struct Date creation_date;
};
void main()
{
     struct sports_team *my_team;
     my_team = (struct sports_team*)malloc(sizeof(struct sports_team)*2);

printf("fill information for teams:\n");


for(int i=0;i<2;i++)
{
    printf("\nenter team name:");
    scanf("%s",&my_team[i].name);
    printf("\nenter team city:");
    scanf("%s",&my_team[i].city);
    printf("\nenter no. of players:");
    scanf("%d",&my_team[i].no_of_players);
    printf("\nenter creation day:");
    scanf("%d",&(my_team[i].creation_date.day));
    printf("\nenter creation month:");
    scanf("%s",&(my_team[i].creation_date.month));
    printf("\nenter creation year:");
    scanf("%d",&(my_team[i].creation_date.year));
    printf("\n\n");
}

 printf("\n information for teams:\n");
for(int i=0;i<2;i++)
{

    printf("%s ",my_team[i].name);

    printf("%s ",my_team[i].city);

    printf("%d ",my_team[i].no_of_players);

    printf("%d ",my_team[i].creation_date.day);

    printf("%s ",my_team[i].creation_date.month);

    printf("%d ",my_team[i].creation_date.year);
    printf("\n\n");
}
free(my_team);
}

you're allocating the structures all right but you're forgetting to allocate memory for char * members: you're writing into uninitialized memory when doing scanf (not to mention that you're passing the address of the pointer, not the pointer itself: don't use & when scanning strings).

For simplicity's sake, you could just put fixed buffer lengths in your structures:

struct Date
{
  int day;
 char month[20];
  int year;
}date;
struct sports_team
{
     char name[100];
    char city[100];
 int no_of_players;
struct Date creation_date;
};

and limit size when scanning (don't use & when scanning strings BTW)

scanf("%99s",my_team[i].name);
scanf("%99s",my_team[i].city);
scanf("%19s",my_team[i].creation_date.month);

使用getchar()而不是scanf()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM