Last active
June 10, 2017 21:19
-
-
Save mikigom/2fca5f215814838b3fbc9cb2e68d8c0c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <string.h> | |
| #include <stdlib.h> | |
| struct nameTag{ | |
| char fname[20]; char lname[20]; | |
| }; | |
| struct nameTag * wrong_getname(void){ | |
| struct nameTag newname; | |
| struct nameTag *p; | |
| printf("Please enter first name:"); | |
| fgets(newname.fname, 20, stdin); | |
| newname.fname[strcspn(newname.fname, "\n")] = '\0'; | |
| printf("Please enter last name:"); | |
| fgets(newname.lname, 20, stdin); | |
| newname.lname[strcspn(newname.lname, "\n")] = '\0'; | |
| p = &newname; | |
| return p; | |
| } | |
| // (*p).fname ======= p->fname | |
| struct nameTag * right_getname(void){ | |
| struct nameTag *p = (struct nameTag *)malloc(sizeof(struct nameTag)); | |
| printf("Please enter first name:"); | |
| fgets(p->fname, 20, stdin); | |
| p->fname[strcspn(p->fname, "\n")] = '\0'; | |
| printf("Please enter last name:"); | |
| fgets(p->lname, 20, stdin); | |
| p->lname[strcspn(p->lname, "\n")] = '\0'; | |
| return p; | |
| } | |
| int main(int argv, char * argc){ | |
| int i; | |
| struct nameTag * local_name_ptr[5]; | |
| for(i = 0; i < 5; ++i) | |
| local_name_ptr[i] = wrong_getname(); | |
| for(i = 0; i < 5; ++i) | |
| printf("i-index first name : %s, last name : %s\n", local_name_ptr[i]->fname, local_name_ptr[i]->lname); | |
| for(i = 0; i < 5; ++i) | |
| local_name_ptr[i] = right_getname(); | |
| for(i = 0; i < 5; ++i) | |
| printf("i-index first name : %s, last name : %s\n", local_name_ptr[i]->fname, local_name_ptr[i]->lname); | |
| for(i = 0; i < 5; ++i) | |
| free((local_name_ptr[i])); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment