상세 컨텐츠

본문 제목

struct(구조체)의 인자 다루기

컴퓨터 관련/프로그래밍 공부

by 열정과 함께 2015. 4. 25. 16:27

본문

언제 한번 정리해둬야지, 하던 것인데 시간 나서 잠깐 하게 되었다. 구조체의 인자를 다루는 법이다. 여기서 보고 갈 구조체의 인자들은 아래와 같다.


  1) 구조체 내부의 변수들

  2) 구조체 내부의 포인터 변수

  3) 구조체 내부의 구조체

  4) 구조체 내부의 구조체, 그 내부의 변수

  5) 구조체 내부의 구조체, 그 내부의 포인터 변수(...)


이러한 과정을 수행하기 위해서 아래와 같은 인자들이 사용되었다.


struct sample1 : 주로 사용하게 될 구조체

struct sample2 : sample1 안에 들어갈 구조체


test : 주로 사용하게 될 sample1 구조체

inside : test 안에 들어갈 sample2 구조체

inside_p : test 안에 들어갈 sample2 구조체 포인터


그러니까 대충 이 정도 해 보는게 목표다.






코드는 아래와 같다.


#include <stdio.h>

#include <string.h>

struct sample2

{

int num2;

int *num2_p;

char c2;

};

struct sample1

{

int num;

int *num_p;

char c;

char str[10];

struct sample2 inside;

struct sample2 *inside_p;

};

int print_struct(struct sample1 object);

int change_struct(struct sample1 *object);

int main()

{

struct sample1 test[2];

struct sample2 inside[2];

int i=0;

int j=22;

int k=33;

test[0].num=0;

test[0].num_p=&i; //test[0].num_p 는 아직 주소값이 할당되지 않음. 따라서 *test[0].num_p = 1 과 같은 연산은 불가

test[0].c='a';

strcpy(test[0].str, "abcd");

*(test[0].num_p)=1; //test[0].num_p 에 주소값이 할당되었음. 따라서 이런 연산이 가능해짐. 단, test[0].num_p 가 NULL 이면 안됨.

inside[0].num2=2;

inside[0].num2_p=&j;

inside[0].c2='b';

test[0].inside=inside[0];

inside[1].num2=3;

inside[1].num2_p=&k;

inside[1].c2='c';

test[0].inside_p=&inside[1];

printf("구조체 내부의 값을 조회합니다. \n");

print_struct(test[0]);

change_struct(&test[0]);

printf("----------바뀐 값을 다시 조회합니다.----------\n");

print_struct(test[0]);

return 0;

}

int print_struct(struct sample1 object)

{

printf("num 변수 : %d \n", object.num);

printf("num_p 변수(주소값) : %d \n", object.num_p);

printf("num_p 변수(저장된 값) : %d \n", *object.num_p);

printf("c 변수 : %c \n", object.c);

printf("str 값 : %s \n", object.str);

printf("inside 구조체의 주소값 : %d \n", &object.inside);

printf("inside 구조체의 num2 : %d \n", object.inside.num2);

printf("inside 구조체의 num2_p 변수(주소값) : %d \n", object.inside.num2_p);

printf("inside 구조체의 num2_p 변수(저장된 값) : %d \n", *object.inside.num2_p);

printf("inside 구조체의 c2 변수 : %d \n", object.inside.c2);

printf("inside_p 구조체의 주소값 : %d \n", object.inside_p);

printf("inside_p 구조체의 num2 변수 : %d \n", object.inside_p->num2);

printf("inside_p 구조체의 num2 변수(주소값) : %d \n", &object.inside_p->num2);

printf("inside_p 구조체의 c2 변수 : %c \n", object.inside_p->c2);

return 0;

}

int change_struct(struct sample1 *object)

{

printf("구조체 변수들의 값을 바꿉니다. \n");

object->num=111;

*(object->num_p)=222;

object->c='k';

strcpy(object->str, "qwert");

object->inside.num2=333;

*(object->inside.num2_p)=444;

object->inside.c2='y';

object->inside_p->num2=555;

*(object->inside_p->num2_p)=666;

object->inside_p->c2='u';

return 0;

}



관련글 더보기

댓글 영역