C 구조체

 

C언어 구조체 정리.

구조체의 정의

struct 구조체명{
     데이터형 변수명;
     데이터형 변수명;
     ...
};

다양한 데이터형을 가진 복수의 데이터를 모아서 다룰 수 있게 한 것.
변수뿐 아니라 배열도 포함할 수 있다.
하나의 프로그램이 복수개의 화일로 구성되어 있을 때 구조체의 정의는 헤더화일등에 넣어 두고 #include 하여 쓰는 경우가 많다.

ex)
struct man{
     int age;
     float height;
     float weight;
     char name[20];
     char character[200];
};

구조체형 변수의 선언

struct 구조체명 변수명;

정의한 구조체는 변수로 선언하여 사용한다.
구조체를 구성하는 각 데이터에대한 접근은 변수명.구조체 내부 해당 변수명의 형태로 이루어진다.

ex)
struct man tom;

tom.age = 20;
tom.height = 180.5;
tom.weight = 83.3;
strcpy(tom.name, "Tom Crow valentaine");
구조체의 포인터로 요소에 접근하는 방법

포인터명->구조체 내부 해당 변수명

ex)
struct man tom;
struct man *ptr;

ptr = &tom;

tom.weight = 75.3;
printf("%f weight\n", tom.weight);
ptr->weight = 92.2;
printf("%f weight\n", tom.weight);
printf("%f weight\n", ptr->weight);
printf("%s is %f weight.\n", ptr->name, ptr->weight);

ex)
#include <stdio.h>
#include <string.h>

struct man{
     int age;
     double height;
     double weight;
     char name[10];
     char character[200];
};

void main(void){

     struct man tom; /*struct man형 변수 선언 */
     struct man *ptr; /*struct man형 포인터 선언 */


     tom.age = 20;
     tom.height = 180.5;
     strcpy(tom.name, "Tom Crow valentaine");

     ptr = &tom;

     tom.weight = 75.3;
     printf("%f weight\n", tom.weight);
     ptr->weight = 92.2;
     printf("%f weight\n", tom.weight);
     printf("%f weight\n", ptr->weight);
     printf("%s is %f weight.\n", ptr->name, ptr->weight);

}

-2007.11.23