본문 바로가기
[C language] C 언어

c언어 총정리 6 - 구조체

by codeomni 2023. 9. 1.
반응형

 

구조체 정의

C언어에서 구조체는 포인터 변수와 배열 포함한 변수을 묶어서 새 자료형을 정의합니다.

 

1
2
3
4
5
struct point
{
    int xpos;
    char name[20];
};

구조체의 이름이 자료형의 이름이 된다.

기본 자료형은 아니지만, 묶어서 새로운 자료형을 만든 것이다.

(사용자 정의 자료형 - user definded data type)

배열도 값이 저장이 가능한 변수의 성격을 가지기 때문에 구조체의 멤버가 될 수 있다.

 


구조체 변수의 선언과 접근

 

구조체 변수로 자료형들을 대상으로 변수를 선언할 수 있다.

 

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

구조체 변수를 선언할 때는 맨 앞에 struct 선언을 추가한다.

생성된 구조체의 접근 기본형식은 구조체 이름.구조체 멤버의 이름이다.

구조체 변수의 멤버에 접근할 때는 .연산자를 사용한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>
#include <string.h>
 
struct person
{
    char name[20];
    int age;
};
 
int main(void)
{
    struct person man;
 
    scanf("%s", man.name);
    scanf("%d"&(man.age));
 
    printf("%s %d \n", man.name, man.age);
 
    return 0;
}

 

구조체의 멤버로 배열이 선언되면 배열의 접근방식을 가지고,

구조체의 멤버로 포인터 변수가 선언되면 포인터 변수의 접근방식을 가진다.

 


구조체 변수의 초기화

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>
#include <string.h>
 
struct person
{
    char name[20];
    int age;
};
 
int main(void)
{
    struct person man = {"codeomni"27};
    printf("%s %d \n", man.name, man.age);
 
    return 0;
}

구조체 변수는 선언과 동시에 초기화가 가능하다.

초기화 방법은 배열의 초기화와 같으며,

구조체의 멤버의 순서대로 넣어주면 된다.

초기화에서는 문자열 저장을 위해 strcpy 함수를 호출하지 않아도 된다.

 


구조체 배열의 선언과 접근

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <stdio.h>
#include <string.h>
 
struct student
{
    char name[20];
    int age;
};
 
int main(void)
{
    struct student arr[3];
    int i;
    for (i=0; i<3; i++)
    {
        printf("학생의 이름과 나이 입력: ");
        scanf("%s %d", arr[i].name, &arr[i].age);
    }
 
    for (i=0; i<3; i++)
        printf("[%s, %d] ", arr[i].name, arr[i].age);
 
    return 0;
}

 

여러 개의 구조체 변수를 선언 시,

구조체 배열을 선언을 사용한다.

 

배열의 선언 방법과 동일하며,

struct    구조체 이름    구조체 배열 이름    [크기] 로 선언한다.

 


구조체 배열의 초기화

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdio.h>
#include <string.h>
 
struct student
{
    char name[20];
    int age;
};
 
int main(void)
{
    struct student arr[3]={
        {"codeomni"27},
        {"tistory"25}
    };
 
    int i;
    for (i=0; i<2; i++)
        printf("[%s, %d] ", arr[i].name, arr[i].age);
 
    return 0;
}

 

구조체 배열을 선언과 함께 초기화할 경우는

중괄호 { } 를 사용해서 초기화 값을 넣어준다.

 


구조체 변수 포인터

 

 

댓글