heenam
chapter 22 구조제와 사용자 정의 자료형1 본문
구조체란 무엇인가?
구조체의 정의
구조체란 하나 이상의 변수를 묶어서 새로운 자료형을 정의하는 도구.
구조체를 기반으로 새로운 자료형을 정의할수 있다.
구조체 변수의 선언과 접근
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);
// 두 개가 같은 의미로 사용되지만 후자를 더 선호함
}
'[Programming Language] > C' 카테고리의 다른 글
Chapter 24 파일 입출력 (0) | 2020.04.17 |
---|---|
chapter 23 구조체와 사용자의 정의 자료형2 (0) | 2020.04.10 |
chapter 21 문자와 문자열 관련 함수 (0) | 2020.04.02 |
chapter 19 함수 포인터와 void 포인터 (0) | 2020.03.18 |
chapter 18 다차원 배열과 포인터의 관계 (0) | 2020.03.18 |