Home > Net >  How to use a pointer in a structure
How to use a pointer in a structure

Time:01-20

If you enter 1 for the first id, 2 for the password, 3 for the second, 4 for the password, 5 for the last destination, and 6 for the d, the results are all displayed as 5 and 6.

I'd appreciate your help.

I wonder that the output values are all 5 and 6. ( You must write a pointer inside the structure. )

void game(struct gameInfo *login, char *id, char *password) {
    printf("game dts:   ");
    fgets(id, sizeof id, stdin);
    login->dts = id;
    cl(login->dts);

    printf("game password:   ");
    fgets(password, sizeof password, stdin);
    login->password = password;
    cl(login->password);
}

void printGame(struct gameInfo *login) {
    for (int i = 1; i < 4; i  ) {
        printf("%d 5s 5s\n", i, (login   i)->dts, (login   i)->password);
        login  ;
    }
}

int main(void) {
    for (int i = 1; i < 4; i  ) {
        gameInfo(login   i, id, password);
        printf("(login   i)-> dst, (login   i)->password);
        login  ;
    }
}

CodePudding user response:

A pointer points to another variable. All your FlightInfos' dates point to the dateStr variable in main, and all their destinations point to the destinationStr variable in main. So when you print what they point to, you're printing the dateStr and destinationStr variables in main.

To solve it you would have to create new "variables" to hold each FlightInfo's date and destination. The obvious way to do it would be to make them arrays instead of pointers, but I guess the purpose of the exercise is to learn pointers - you can use malloc to allocate some memory space for long-term usage, and then access it by pointer. (Don't try to store the date and destination in local variable arrays inside fillFlightInfo, since you'll get a similar problem - when it returns, the local variables are deleted and the space will be reused for the next call)

  •  Tags:  
  • c
  • Related