aaa 7

Programming Learning Diary

struct 구조체 // 메모리 구조와 포인터,구조체의 사용으로 인한 깨달음

페이지 정보

작성일 19-12-05 15:39

본문

1년전쯤 처음으로 프로그래밍을 입문하였을 때에 도저히 이해하지 못했던 구조체..

다시 공부해보니 이런거군아 싶은 생각을 적어보도록 하겠다



예제를 들어가며 적어보도록 하겠다.


#include <stdio.h>

int main() {

typedef struct { int x, y; } Point;   //struct Point { int x, y; }; 과 같이 쓸 수도 있다.

Point p;

p.x = 3;

p.y = 4;


printf("(%d,%d)",p.x,p.y);

}


앞서 적었던 typedef 는 어떤 타입을 정의하는 녀석이다 

위의 빨간 부분을 해석해보자면 

typedef 타입을 정의해보겠습니다 struct 이 타입이 가질 구조체는 {int x,y;} int 형자료 x와 y 입니다. Point 이녀석을 'Point' 라고 지정하겠습니다 .


위의 예제에서 Point 를 p 로 정의하고였고 p.x 에 3을 담고 p.y에 4를 담았다.  변수명에 . 을 붙이고 해당 구조체를 붙이면 사용가능하다   

이러한 형식은 객체지향 언어에서 많이 본 형식이다 (JAVA) 

이렇게 C++을 배우면서  객체 지향형 언어들도 메모리구조에서 보면 이것과 비슷하겠구나 라는 생각이 들었다. 

포인터를 알고 메모리 구조에 어떻게 정보들이 쌓이겠구나를 파악하고 배열의 사용,배열과 포인터의 관계, typedef, struct(구조체)를 보니 
프로그래밍이 어떻게 돌아가는 구나에 좀더 가까워지는 기분이고 널부러 져있던 퍼즐이 맞춰지는 순간을 마주한 것 같다.

깨달음을 주는 소중한 시간이였다. 




============================================================================================================================================



다음은 구조체를 활용한 코드이다.

 

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

};

int main() {
ProductInfo myproduct = {4797283,"제주 한라봉",19900};
printf("상품 번호:%d\n",myproduct.num);
printf("상품 이름:%s\n", myproduct.name);
printf("상품 가격:%d\n", myproduct.cost);

printf("sizeof(myproduct)=%d\n",sizeof(myproduct));
}


결과
 5aca6d7eafb6fb4232f623c2d7ee8ac2_1575532356_3767.png 


마치 자바의 class 구조를 보는것 같은 느낌이 든다. 


추가적으로 다음 구조체를 직접 가르켜 서 (구조체포인터) 출력을 할 수도 있다.

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

}; 

int main() {
ProductInfo myproduct = {4797283,"제주 한라봉",19900};
ProductInfo *ptr_product = &myproduct;

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

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

printf("sizeof(myproduct)=%d\n",sizeof(myproduct));
}


결과
5aca6d7eafb6fb4232f623c2d7ee8ac2_1575533319_9094.png





세일 함수 추가사용
 
struct ProductInfo {
int num; //4B
char name[100]; //100B
int cost; //4B

};
void productSale(ProductInfo *p, int percent) {
p->cost -= p->cost * percent / 100;
}
int main() {
ProductInfo myproduct = { 4797283,"제주 한라봉",20000 };
productSale(&myproduct,10);
printf("상품 번호:%d\n", myproduct.num);
printf("상품 이름:%s\n", myproduct.name);
printf("상품 가격:%d\n", myproduct.cost);
}

5aca6d7eafb6fb4232f623c2d7ee8ac2_1575533747_5258.png


포인터를 활용한 구조체 swap 하기

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

};
void productSwap(ProductInfo *a, ProductInfo* b) {
ProductInfo tmp = *a;
*a = *b;
*b = tmp;
}
int main() {
ProductInfo myproduct = { 4797283,"제주 한라봉",20000 };
ProductInfo otherproduct = { 4797284,"성주 꿀참외",10000 };
productSwap(&myproduct, &otherproduct);
printf("상품 번호:%d\n", myproduct.num);
printf("상품 이름:%s\n", myproduct.name);
printf("상품 가격:%d\n", myproduct.cost);
}

5aca6d7eafb6fb4232f623c2d7ee8ac2_1575533960_071.png
 
=======================================================================================================================================

구조체에 함수넣기



예제1



struct Time {

int h, m, s;


int totalSec() {

return 3600*h + 60 *m + s;

}

};



int main() {

Time t = { 1,22,48 };

printf("%d\n", t.totalSec());



예제2



struct Point {

int x, y;

void moveRight() { x++; }

void moveLeft() { x--; }

void moveUp() { y++; }

void moveDown() { y--; }


};

int main() {

Point p = { 2,5 };

p.moveDown();

p.moveRight();

printf("(%d,%d)",p.x,p.y);

5aca6d7eafb6fb4232f623c2d7ee8ac2_1575535029_0484.png
 
==========================================================================================================================
예제


typedef int Point[2];

typedef Point *PointPtr;

int main() {

Point p = { 3,4 }; //int p[2]={3,4};

PointPtr pp= &p;  //Point *pp=&p;

printf("(%d,%d,%d )",**pp,(*pp)[0],(*pp)[1]);



================================================================================

출력 결과

5aca6d7eafb6fb4232f623c2d7ee8ac2_1575535652_419.png