Data Structure

구조체

Denken_Y 2019. 6. 14. 03:02

  구조체(Structure)는 배열과 비슷하지만 서로 다른 자료형을 하나의 그룹으로 묶는다는 점에서 차이가 있다. 배열의 경우엔 같은 자료형의 자료들을 묶었지만 구조체는 서로 다른 자료형을 묶는다.

struct student {
	char name[21];
    	int year;
    	float score;
};	

위의 코드는 구조체를 정의한 하나의 예제이다. 주의해야할점은 이것은 구조체의 자료형을 선언한 것이지 구조체 변수를 선언한것은 아니다. struct 선언만 해놓으면 이후 구조체 변수 선언때도 struct를 붙여줘야하기 때문에 typedef을 이용한다.

typedef struct student_type {
	char name[21];
    	int year;
    	float score;
} student;

 

student 구조체를 선언하고 포인터를 이용하여 값을 변경해보는 예제이다. student의 포인터를 선언한 후 -> 연산으로 포인터가 가르키는 std_yoo의 값 변경을 해보았다.

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

typedef struct student_type {
	char name[21];
    	int year;
    	float score;
} student;

int main()
{
    student std_yoo;
    student *ptr_std = NULL;
    
    ptr_std = &std_yoo;
    
    strcpy(ptr_std->name, "yoo");
    ptr_std->score = 91.1f;
    ptr_std->year = 1995;
    
    printf("%1f\n", ptr_std->score);
    
    std_yoo.score = 95.5;
    
    printf("%s\n", ptr_std->name);
    printf("%1f\n", ptr_std->score);
    printf("%d\n", ptr_std->year);

    return 0;
}