How to create a struct on the stack in C?

℡╲_俬逩灬. 提交于 2019-11-28 20:47:06

问题


I understand how to create a struct on the heap using malloc. Was looking for some documentation regarding creating a struct in C on the stack but all docs. seem to talk about struct creation on heap only.


回答1:


The same way you declare any variable on the stack:

struct my_struct {...};

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



回答2:


To declare a struct on the stack simply declare it as a normal / non-pointer value

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

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



回答3:


I got it to work this way:

#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;
}


来源:https://stackoverflow.com/questions/10916799/how-to-create-a-struct-on-the-stack-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!