본문 바로가기

컴퓨터 언어/C

Typedef와 구조체

배운내용 정리

typedef는 type define의 약자로, 기존에 있는 형을 정의하는 것이다.

구조체는 여러 자료형을 가진 변수들을 하나로 묶어 자료형으로 사용할 수 있도록 하는 것이다.

 Struct는 형식을 지정하고, typedef는 형을 정의하는 것이다.

typedef int Int32;
Int32 n = 20;
printf("%d", n);

Int32를 int형으로 정의하고 적용한 모습이다. 20이 출력된다.

typedef int Pair[2];
Pair point = { 3,4 }; //int point[2] = {3, 4}
printf("(%d, %d)\n", point[0], point[1])

배열을 이용해서 간단한 코드를 짜보았다. Pair을 int형으로 정의하고 적용한 모습이다.

typedef struct {
		int x, y;
	} Pair;

Pair p; //int p[2]
p.x = 3;
p.y = 4;

구조체를 typedef로 선언할 수도 있다. typedef struct {}로 구조체를 선언한 후, 뒤에 구조체 이름을 설정하여 적으면 된다. 

#include <stdio.h>

struct ProductInfo {
	int num;
	char name[100];
	int cost;
};

void productSale(ProductInfo *p, int percent) {
	p->cost -= p->cost * percent / 100;
}

void productSwap(ProductInfo* a, ProductInfo* b) {
	ProductInfo tmp = *a;
	*a = *b;
	*b = tmp;
}


int main() {
	ProductInfo myProduct{ 475645, "제주 한라봉",20000 };
	ProductInfo otherProduct{ 475645, "성주 꿀참외",10000 };
	ProductInfo* ptr_product = &myProduct;

	productSale(&myProduct, 10);
	productSwap(&myProduct, &otherProduct);

	printf("상품 번호 : %d\n", ptr_product->num); //(*ptr_product).num 과 같은 뜻
	printf("상품 이름 : %s\n", ptr_product->name);
	printf("가     격 : %d\n", ptr_product->cost);
}

구조체와 포인터를 이용해서 만든 코드이다. 

'컴퓨터 언어 > C' 카테고리의 다른 글

비트 연산  (0) 2022.03.11
상수 만들기  (0) 2022.03.10
재귀함수  (0) 2022.02.28
프로토타입  (0) 2022.02.28
함수의 반환  (0) 2022.02.28