구조체 형태

#include <stdio.h>

struct student {      //구조체 정의
	int number;       //구조체 멤버 변수
	char name[10];
	double grade;
};

int main(void)
{
	struct student s1; //구조체 변수 선언
           ·
           ·
           ·
}

 

구조체 변수의 특징

1. 구조체 대입 - 가능

#include <stdio.h>

struct point {
	int x;
	int y;
};

int main(void)
{
	struct point p1 = { 1, 2 };
	struct point p2 = { 3, 4 };

	p2 = p1;

	printf("%d %d %d %d", p1.x, p1.y, p2.x, p2.y); //결과확인

	return 0;
}

결과는 1 2 1 2로 대입이 제대로 된 것을 확인할 수 있었다.

 

2. 구조체 비교 - 불가능

#include <stdio.h>

struct point {
	int x;
	int y;
};

int main(void)
{
	struct point p1 = { 1, 2 };
	struct point p2 = { 3, 4 };

	if (p1 == p2) //컴파일 오류
	{
		printf("p1과 p2가 같습니다.");
	}

	return 0;
}

바로 이렇게 에러가 난다.

 

구조체 배열

기본 형태는 이렇다.

#include <stdio.h>
#include <string.h>

struct student {
	int number;
	char name[20];
	double grade;
};

int main(void)
{
	struct student list[100];
	
	list[2].number = 17;
	strcpy(list[2].name, "Lee");
	list[2].grade = 170;

	return 0;
}

 

구조체의 형태와 특징, 배열을 정리해봤다. 다음에는 구조체의 포인터, 공용체, 열거형에 대해 복습을 할 계획이다.

'프로그래밍 언어 > c' 카테고리의 다른 글

C언어 구조체, 공용체, 열거형 (2)  (0) 2021.01.20
C언어 동적메모리  (0) 2021.01.20
구조체와 공용체  (0) 2021.01.10
포인터와 함수 그리고 void형 포인터  (2) 2021.01.07
c언어 (1) - 포인터  (0) 2021.01.05

+ Recent posts