Could not able to understand in line 13 that how a pointer function is assigned to a struct . And on line 15 *who is allocated with some memory space . normally a pointer is assigned to an address but how this way serves the purpose... By the way it is from the book Learn code the hard way...Please shed some light...
Code:1 #include <stdio.h> 2 #include <assert.h> 3 #include <stdlib.h> 4 #include <string.h> 5 6 struct Person { 7 char *name; 8 int age; 9 int height; 10 int weight; 11 }; 12 13 struct Person *Person_create(char *name, int age, int height, int weight) 14 { 15 struct Person *who = malloc(sizeof(struct Person)); 16 assert(who != NULL); 17 18 who->name = strdup(name); 19 who->age = age; 20 who->height = height; 21 who->weight = weight; 22 23 return who; 24 } 25 26 void Person_destroy(struct Person *who) 27 { 28 assert(who != NULL); 29 30 free(who->name); 31 free(who); 32 } 33 34 void Person_print(struct Person *who) 35 { 36 printf("Name: %s\n", who->name); 37 printf("\tAge: %d\n", who->age); 38 printf("\tHeight: %d\n", who->height); 39 printf("\tWeight: %d\n", who->weight); 40 } 41 42 int main(int argc, char *argv[]) 43 { 44 // make two people structures 45 struct Person *joe = Person_create( 46 "Joe Alex", 32, 64, 140); 47 48 struct Person *frank = Person_create( 49 "Frank Blank", 20, 72, 180); 50 51 // print them out and where they are in memory 52 printf("Joe is at memory location %p:\n", joe); 53 Person_print(joe); 54 55 printf("Frank is at memory location %p:\n", frank); 56 Person_print(frank); 57 58 // make everyone age 20 years and print them again 59 joe->age += 20; 60 joe->height -= 2; 61 joe->weight += 40; 62 Person_print(joe); 63 64 frank->age += 20; 65 frank->weight += 20; 66 Person_print(frank); 67 68 // destroy them both so we clean up 69 Person_destroy(joe); 70 Person_destroy(frank); 71 72 return 0; 73 }
I tried to replace that function with the my understanding and the code works fine.....
Code:int create_profile(char *name,int age,int height,int weight) { struct Nani *item = malloc(sizeof(struct phani)); assert(item != NULL); item->heissen = name; item->alt = age; item->grosse = height; item->gewicht = weight; return item; }
Thanks n Regards
Max



1Likes
LinkBack URL
About LinkBacks




but if i want 1000 struct person i would do this