programing

C의 스택에 구조를 작성하려면 어떻게 해야 합니까?

goodcopy 2022. 7. 19. 21:33
반응형

C의 스택에 구조를 작성하려면 어떻게 해야 합니까?

작성 방법을 이해하고 있습니다.struct을 사용하여 산더미처럼 쌓이다malloc의 작성에 관한 문서를 찾고 있었습니다.struct모든 문서를 제외하고 스택의 C에 있습니다.힙에 대한 구조 생성에 대해서만 이야기하는 것 같습니다.

스택상의 변수를 선언하는 것과 같은 방법을 사용합니다.

struct my_struct {...};

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

스택에서 구조체를 선언하려면 해당 구조체를 일반/비포인터 값으로 선언하기만 하면 됩니다.

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

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

함수를 사용한 17.4 Extra Credit(제드의 책 "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;
}

이런 식으로 작동시켰어요

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

언급URL : https://stackoverflow.com/questions/10916799/how-to-create-a-struct-on-the-stack-in-c

반응형