Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

heenam

chapter 22 구조제와 사용자 정의 자료형1 본문

[Programming Language]/C

chapter 22 구조제와 사용자 정의 자료형1

znzltiq 2020. 4. 10. 00:58

구조체란 무엇인가?

 구조체의 정의

  구조체란 하나 이상의 변수를 묶어서 새로운 자료형을 정의하는 도구.

  구조체를 기반으로 새로운 자료형을 정의할수 있다.

구조체 변수의 선언과 접근

  struct type_name val_name; // 구조체 변수선언의 기본 형태

  맨 앞에는 struct 선언을 추가해야 하며, 이어서 구조체의 이름과 구조체 변수의 이름을 선언해야 한다.

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


struct people // 구조체 people의 정의
{
    char name[10];
    char phoneNum[20];
    int age;
};

int main()
{
	struct people man1, man2; // 구조체의 변수
    
    printf("name: "); scanf("%s", man1.name);
    printf("phoneNum: "); scanf("%s", man1.phoneNum);
    printf("age: "); scanf("%d", &(man1.age));

    printf("name : %s\n", man1.name);
    printf("phoneNum : %s\n", man1.phoneNum);
    printf("age : %d\n", man1.age);


}

 구조체의 초기화

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

struct point
{
    int xpos;
    int ypos;
};

struct people
{
    char name[10];
    char phoneNum[20];
    int age;
};

int main()
{
    struct point pos = {10, 20}; // point 구조체 변수값에 바로 저장
    struct people man ={"heenam", "283-2476", 27}; // people 구조체 변수값에 바로 저장

    printf("%d %d\n", pos.xpos, pos.ypos);
    printf("%s %s %d\n", man.name, man.phoneNum, man.age);
}

구조체와 배열 그리고 포인터

 구조체 배열의 선언과 접근

  구조체 배열의 선언방법은 일반적인 배열의 선언방법과 동일하다.

#include <stdio.h>

struct point
{
    int xpos;
    int ypos;
};

int main()
{
    struct point pos[3];
    for (int i = 0; i < 3; i++){
        scanf("%d %d", &pos[i].xpos, &pos[i].ypos );
    }
    for (int i = 0; i < 3; i++){
        printf("[%d, %d]\n", pos[i].xpos, pos[i].ypos);
    }

}

 구조체 배열의 초기화

#include <stdio.h>


struct people
{
    char name[10];
    char phoneNum[20];
    int age;
};

int main()
{
    struct people person[3] = {
        {"heenam", "283-2476", 27},
        {"hana", "465-7532", 23},
        {"jihun", "654-354", 28}
    };

    for (int i = 0; i < 3; i++){
        printf("%s %s %d\n", person[i].name, person[i].phoneNum, person[i].age);
    }

}

 구조체 변수와 포인터

#include <stdio.h>


struct point
{
    int xpos;
    int ypos;
};

int main()
{
    struct point pos1 = {1, 2};
    struct point * pptr = &pos1;

    (*pptr).xpos += 4;
    (*pptr).ypos += 5;

    printf("[%d %d]\n", (*pptr).xpos, pptr -> ypos);
    // 두 개가 같은 의미로 사용되지만 후자를 더 선호함

}