简体   繁体   中英

How to access a pointer of struct in a struct using a function?

Actually I don't know what to except to ask for explanation to something I don't know what to call. I want to modify the "Date *d" which is in "Train *t".

typedef struct date{
      char dateDepart[MAX_VAL];
      int mois;
      int jour;
      int annee;
}Date;
typedef struct train{
    int numero;
    char villeDepart[MAX_VAL];
    char villeArrivee[MAX_VAL];
    Date *d;
}Train;

And I got this function that modifies the Train variables.

void getTrain(Train *t){
    printf("Saisie Train: ");
    scanf("%d",&t->numero);
    printf("Ville Depart: ");
    scanf("%s",&t->villeDepart);
    printf("Ville Arrivee: ");
    scanf("%s",&t->villeArrivee);
    printf("=========== Date Depart ============\n");
    getDate(t->d);
    printf("====================================\n");
}

And when it comes to getDate it doesn't work and the executable program quits. I guess it's segmentation fault. I am not an expert to be honest. but i'll be more than happy if someone helps me with the problem of getTrain . I guess there is a problem with the pointer. I don't know.

This is the getDate function

void getDate(Date *d){
    printf("Jour: ");
    scanf("%d",&d->jour);
    printf("Mois: ");
    scanf("%d",&d->mois);
    printf("Annee: ");
    scanf("%d",&d->annee);
    char tmp [MAX_VAL]; itoa(d->jour,tmp,10);
    strcat(d->dateDepart,tmp);
    strcat(d->dateDepart,"/");
    itoa(d->mois,tmp,10);
    strcat(d->dateDepart,tmp);
    strcat(d->dateDepart,"/");
    itoa(d->annee,tmp,10);
    strcat(d->dateDepart,tmp);
}

and this is the main code.

int main(){
    Train *t;
    getTrain(t);
    putTrain(t);
}

putTrain is just for printing.

You are trying to access to pointers that are not initialized. If you work with pointers, you need to properly assign address to these pointers, and in your case, dynamically allocated memory blocks:

Train *t = (Train*)malloc(sizeof(Train));
t->d = (Date*)malloc(sizeof(Date));

// do something...

free(t->d);
free(t);
t = NULL;

Notice that you are not forced to work with dynamically allocated memory, you could for example declare your Train structure as follow:

typedef struct train{
  int numero;
  char villeDepart[MAX_VAL];
  char villeArrivee[MAX_VAL];
  Date d;                     //< not a pointer
} Train;

Then use your structures as follow:

int main(){
  Train t;
  getTrain(&t);  //< reference (pointer) to t
  putTrain(&t);  //< reference (pointer) to t
}

In this case, you also have to modify the way you access to d to pass to getDate function:

getDate(&t->d); //< reference (pointer) to d member of t

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