C,C++

C,C++ : 구조체 포인트

디자이너 기즈모 2023. 7. 31. 20:52

https://youtu.be/nprq56hdAqU

#include <stdio.h>

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

int main1_1()
{
	ProductInfo myProduct = { 12323223,"제주 한라봉", 20000 };
	
	ProductInfo* ptr_product = &myProduct;

	printf("상품 번호 : %d\n", (*ptr_product).cost);
	printf("상품 이름 : %s\n", (*ptr_product).name);
	printf("가     격 : %d\n", (*ptr_product).num);
	return 0;
}

int main1_2()
{
	ProductInfo myProduct = { 12323223,"제주 한라봉", 20000 };

	ProductInfo* ptr_product = &myProduct;

	//(*a).b == a->b

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

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

int main1_3()
{
	ProductInfo myProduct = { 12323223,"제주 한라봉", 20000 };


	productSale(myProduct, 10);

	ProductInfo* ptr_product = &myProduct;

	//(*a).b == a->b

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


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

int main1_4()
{
	ProductInfo myProduct{ 12323223,"제주 한라봉", 20000 };
	ProductInfo otherPro{ 12323223,"성주 꿀참외", 10000 };

	productSwap(&myProduct, &otherPro);
	//(*a).b == a->b

	printf("상품 번호 : %d\n", myProduct.num);
	printf("상품 이름 : %s\n", myProduct.name);
	printf("가     격 : %d\n", myProduct.cost);// (*ptr_product).cost);
	return 0;
}

int main()
{
	main1_1();
	printf("\n");
	main1_2();
	printf("\n");
	main1_3();
	printf("\n");
	main1_4();

	return 0;
}