str*_*eek 50 c heap-memory stack-memory
我理解如何struct在堆上创建使用malloc.正在寻找struct关于在堆栈上创建一个C而不是所有文档的一些文档.似乎只谈论堆上的结构创建.
har*_*ald 54
与在堆栈上声明任何变量的方式相同:
struct my_struct {...};
int main(int argc, char **argv)
{
    struct my_struct my_variable;     // Declare struct on stack
    .
    .
    .
}
Jar*_*Par 24
要在堆栈上声明结构,只需将其声明为普通/非指针值
typedef struct { 
  int field1;
  int field2;
} C;
void foo() { 
  C local;
  local.field1 = 42;
}
小智 6
使用函数回答 17.4 Extra Credit(在 Zed 的书“Learn C the Hard Way”中)
#include <stdio.h>
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;
}