How to create a struct on the stack in C?

后端 未结 4 1784
遇见更好的自我
遇见更好的自我 2020-12-23 19:18

I understand how to create a struct on the heap using malloc. Was looking for some documentation regarding creating a struct in C on t

4条回答
  •  孤城傲影
    2020-12-23 20:10

    an answer to 17.4 Extra Credit (in Zed's book "Learn C the Hard Way") using functions

    #include 
    
    struct Person {
            char *name;
            int age;
            int height;
            int weight;
    };
    
    
    struct Person Person_create(char *name, int age, int height, int weight)
    {
            struct Person who;
            who.name = name;
            who.age = age;
            who.height = height;
            who.weight = weight;
    
            return who;
    }
    
    
    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 two people structures 
            struct Person joe = Person_create("Joe Alex", 32, 64, 140);
            struct Person frank = Person_create("Frank Blank", 20, 72, 180);
    
            //print them out and where they are in memory
            printf("Joe is at memory location %p:\n", &joe);
            Person_print(joe);
    
            printf("Frank is at memory location %p:\n", &frank);
            Person_print(frank);
    
            // make everyone age 20 and 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;
    }
    

提交回复
热议问题