struct - Learn C the hard way excercise 16 -
i inexperienced programmer working through learn c hard way , stuck on credit exercise.
http://c.learncodethehardway.org/book/ex16.html
i trying adapt code , making struct on stack instead of heap code giving me segmentation fault , unsure why or how proceed. advice appreciated.
#include <stdio.h> #include <stdlib.h> #include <string.h> struct person { char *name; int age; int height; int weight; }; void person_create(struct person p,char *name,int age,int height,int weight) { p.name = name; p.age = age; p.height = height; p.weight = weight; } void person_print(struct person who) { printf("name: %s\n", who.name); printf("\tage: %d\n", who.age); printf("\theight: %d\n", who.height); printf("\tweight: %d\n", who.weight); } int main(int argc, char *argv[]) { // make 2 people structures struct person joe; struct person frank; person_create( joe,"joe alex",32,64,140); person_create( frank,"frank blank",20,72,180); // print them out person_print(joe); person_print(frank); ; // make age 20 years , print them again joe.age += 20; joe.height -= 2; joe.weight += 40; person_print(joe); frank.age += 20; frank.weight += 20; person_print(frank); return 0; }
the reason code produces errors @ runtime c passes struct
s value, meaning following assignments inside person_create
have no effect:
p.name = name; p.age = age; p.height = height; p.weight = weight;
this makes no changes joe
, frank
inside main()
, leading undefined behavior on printing, because name
data member of struct person
remains uninitialized.
in order fix problem, pass struct person
pointer, , apply ->
operator in place of .
operator:
void person_create(struct person *p,char *name,int age,int height,int weight) { p->name = name; p->age = age; p->height = height; p->weight = weight; } ... person_create(&joe, "joe alex", 32, 64, 140); // ^ pass address
it asking me not use pointers or malloc, , says advice creating struct on stack
your code creates struct
s on stack. if rid of pointers completely, change person_create
*return` new person, this:
struct person person_create(char *name,int age,int height,int weight) { struct person p; p.name = name; p.age = age; p.height = height; p.weight = weight; return p; } ... joe = person_create("joe alex", 32, 64, 140);
Comments
Post a Comment