티스토리 뷰
728x90
SMALL
구조체 : 하나 이상의 변수를 묶어서 새로운 자료형을 정의하는 도구
struct person{
char name[20];
char phoneNum[20];
int age;
};
구조체 변수 : struct type_name val_name;
struct person man;
구조체 변수에 접근
man.name="홍길동";
구조체 변수에 문자열 저장을 하려면 strcpy 함수를 호출해야 한다. ex) strcpy(man1.name, "홍길동");
구조체 변수에 초기화 과정에서는 문자열 저장을 위해서 strcpy 함수를 호출하지 않아도 된다.
ex) struct person man={"홍길동", "010", 22};
구조체 배열
struct point arr[4];
구조체 변수와 포인터
#include <stdio.h>
struct point
{
int xpos;
int ypos;
};
int main(void)
{
struct point pos1 = { 1, 2 };
struct point pos2 = { 100, 200 };
struct point* pptr = &pos1;
(*pptr).xpos += 4;
(*pptr).ypos += 5;
printf("[%d, %d] \n", pptr->xpos, pptr->ypos);
pptr = &pos2;
pptr->xpos += 1;
pptr->ypos += 2;
printf("[%d, %d] \n", (*pptr).xpos, (*pptr).ypos);
return 0;
}
(*pptr).xpos+=4; ======== pptr->xpos+=4;
포인터 변수를 구조체의 멤버로 선언하기
#include <stdio.h>
struct point
{
int xpos;
int ypos;
};
struct circle
{
double radius;
struct point* center;
};
int main(void)
{
struct point cen = { 2, 7 };
double rad = 5.5;
struct circle ring = { rad, &cen };
printf("원의 반지름: %g \n", ring.radius);
printf("원의 중심 [%d, %d] \n", (ring.center)->xpos, (ring.center)->ypos);
return 0;
}
#include <stdio.h>
struct point
{
int xpos;
int ypos;
struct point* ptr;
};
int main(void)
{
struct point pos1 = { 1, 1 };
struct point pos2 = { 2, 2 };
struct point pos3 = { 3, 3 };
pos1.ptr = &pos2; // pos1과 pos2를 연결
pos2.ptr = &pos3; // pos2와 pos3를 연결
pos3.ptr = &pos1; // pos3를 pos1과 연결
printf("점의 연결관계... \n");
printf("[%d, %d]와(과) [%d, %d] 연결 \n",
pos1.xpos, pos1.ypos, pos1.ptr->xpos, pos1.ptr->ypos);
printf("[%d, %d]와(과) [%d, %d] 연결 \n",
pos2.xpos, pos2.ypos, pos2.ptr->xpos, pos2.ptr->ypos);
printf("[%d, %d]와(과) [%d, %d] 연결 \n",
pos3.xpos, pos3.ypos, pos3.ptr->xpos, pos3.ptr->ypos);
return 0;
}
구조체 변수의 주소 값은 구조체 변수의 첫 번째 멤버의 주소 값과 동일하다.
#include <stdio.h>
struct point
{
int xpos;
int ypos;
};
struct person
{
char name[20];
char phoneNum[20];
int age;
};
int main(void)
{
struct point pos={10, 20};
struct person man={"이승기", "010-1212-0001", 21};
printf("%p %p \n", &pos, &pos.xpos);
printf("%p %p \n", &man, man.name);
return 0;
}
728x90
LIST
'책 > 윤성우 열혈 C 프로그래밍' 카테고리의 다른 글
파일 입출력1 (0) | 2020.09.23 |
---|---|
구조체와 사용자 정의 자료형2 (0) | 2020.09.21 |
문자와 문자열 관련 함수 (0) | 2020.09.19 |
c언어 난수생성 (0) | 2020.09.19 |
달팽이 배열 (0) | 2020.09.19 |
댓글
공지사항