如何创建在C堆栈上的结构?(How to create a struct on the stack

2019-06-25 06:04发布

我知道如何创建一个struct上使用堆malloc 。 一直在寻找有关创建一些文件struct栈,但所有的文档上用C。 似乎谈论只堆结构的创建。

Answer 1:

声明堆栈上的任何变量用同样的方法:

struct my_struct {...};

int main(int argc, char **argv)
{
    struct my_struct my_variable;     // Declare struct on stack
    .
    .
    .
}


Answer 2:

申报堆栈上的结构简单地声明它作为一个正常/非指针值

typedef struct { 
  int field1;
  int field2;
} C;

void foo() { 
  C local;
  local.field1 = 42;
}


Answer 3:

我得到它的工作是这样的:

#include <stdio.h>

struct Person {
  char *name;
  int age;
  int height;
  int weight;
};

int main(int argc, char **argv)
{
  struct Person frank;
  frank.name = "Frank";
  frank.age = 41;
  frank.height = 51;
  frank.weight = 125;

  printf("Hi my name is %s.\n", frank.name);
  printf("I am %d yeads old.\n", frank.age);
  printf("I am %d inches tall.\n", frank.height);
  printf("And I weigh %d lbs.\n", frank.weight);

  printf("\n-----\n");

  struct Person joe;
  joe.name = "Joe";
  joe.age = 50;
  joe.height = 93;
  joe.weight = 200;

  printf("Hi my name is %s.\n", joe.name);
  printf("I am %d years old.\n", joe.age);
  printf("I am %d inches tall.\n", joe.height);
  printf("And I weigh %d lbs.\n", joe.weight);

  return 0;
}


文章来源: How to create a struct on the stack in C?