C언어 구조체

1 개념[ | ]

C언어 구조체
C Language Structure
  • 구조체는 구조화된 데이타를 처리할때 사용. 즉, 의미있는 데이타 덩어리 (본 페이지의 예시는 위치를 나타내는 x, y좌표를 각각 하나의 데이타로 구조화함)
  • C언어에서는 'struct' 를 사용하여 구조체 정의

2 하나만 생성[ | ]

struct { int x; int y; } Pos;
→ struct { int x; int y; }를 int, char 와 같이 생각하면 됨

3 여러개 생성[ | ]

struct PosTag { int x; int y; };
struct PosTag Pos1;
struct PosTag Pos2;
→ 매번 구조체 변수를 생성할 때 struct { int x; int y; } Pos1;, struct { int x; int y; } Pos2; 와 같이 구조체 전체를 사용하여 변수를 생성하기 불편하기 때문에 PosTag를 통하여 간단하게 구조체 변수 생성이 가능

4 typedef를 사용하여 생성[ | ]

typedef struct { int x; int y; } PosType;
PosType Pos1;
PosType Pos2;

5 예시[ | ]

  • 구조체를 하나만 생성하는 경우
#include <stdio.h>

struct { int x; int y; } Pos;

int main()
{
	Pos.x = 1;
	Pos.y = 2;

	printf("x = %d, y = %d\n", Pos.x, Pos.y);

	return 0;
}
  • 구조체를 여러개 생성하는 경우
#include <stdio.h>

struct posTag { int x; int y; };

int main()
{
	struct posTag Pos = { 1, 2 };
	struct posTag Pos2 = { 3, 4 };

	printf("x = %d, y = %d\n", Pos.x, Pos.y);
	printf("x = %d, y = %d\n", Pos2.x, Pos2.y);

	return 0;
}
  • typedef를 통해 구조체를 생성하는 경우
#include <stdio.h>

typedef struct { int x; int y; } PosType;

int main()
{
	PosType Pos = { 1, 2 };
	PosType Pos2 = { 3, 4 };

	printf("x = %d, y = %d\n", Pos.x, Pos.y);
	printf("x = %d, y = %d\n", Pos2.x, Pos2.y);

	return 0;
}

6 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}