본문 바로가기

programming language/C 언어

열혈 ( c ) chapter 22-구조체의 정의

 

<두 점의 거리 계산 공식을 별도의 함수로 정의해준 예시>

 

#include<stdio.h>
#include<math.h>
struct point
{
	int xpos;
	int ypos;
};

int calculate(int A, int B,int C,int D)
{
	return sqrt((A - B) * (A - B) + (C - D) * (C - D));
}

int main(void)
{
	struct point pos1, pos2;
	double distance;
	
	fputs("point1 pos: ", stdout);
	scanf("%d %d", &pos1.xpos, &pos1.ypos);

	fputs("point2 pos: ", stdout);
	scanf("%d %d", &pos2.xpos, &pos2.ypos);

	distance = calculate(pos1.xpos, pos2.xpos, pos1.ypos, pos2.ypos);
	printf("두 점의 거리는 %g 입니다.\n", distance);
	return 0;

}

 

위 코드는 형변환에서의 오류가 있었다. 그래서 아래와 같이 함수의 반환형을 double형으로 바꿔주었다.

 

<형 변환의 오류가 있어서 함수의 반환형을 int형이 아닌 double형으로 반환되게 해주었다.>

 

#include<stdio.h>
#include<math.h>
struct point
{
	int xpos;
	int ypos;
};

 double calculate(int A, int B, int C, int D)
{
	return sqrt((A - B) * (A - B) + (C - D) * (C - D));
}

int main(void)
{
	struct point pos1, pos2;
	double distance;

	fputs("point1 pos: ", stdout);
	scanf("%d %d", &pos1.xpos, &pos1.ypos);

	fputs("point2 pos: ", stdout);
	scanf("%d %d", &pos2.xpos, &pos2.ypos);

	distance = calculate(pos1.xpos, pos2.xpos, pos1.ypos, pos2.ypos);
	printf("두 점의 거리는 %g 입니다.\n", distance);
	return 0;

}

 

<형변환 이해 예시>

 

#include<stdio.h>
#include<math.h>
int main(void)
{
	int num1 = 32;
	int num2 = 7;
	float num3;

	num3 = num1 / num2; 
	다.
	printf("%f\n", num3);

	num3 = (float)num1 / num2; 
	printf("%f\n", num3);
	return 0;
}

 

warning C4244: '=': 'int'에서 'float'(으)로 변환하면서 데이터가 손실될 수 있습니다. -->컴파일 경고 발생

 

num1 / num2 의 연산결과로 정수 4가 나오고, num3에 4.0 이 저장된다. 이때 num3은 float형이라 int랑 자료형이 달라 컴파일 경고가 발생한다.

 

num3 = (float)num1 / num2; 

 

(float)num1은 num1에 저장된 값을 float형으로 반환하라는 뜻이다. 이때 사용되는 소괄호는 ( ) '형변환 연산자' 라하며, 연산결과로 변환된 값이 반환된다.

 

위 형변환 연산의 결과로 아래와 같은 문장의 형태가 된다.

num3 = 32.0 / num2; 

 

이어서 나눗셈을 진행해야 하는데, 산술연산의 형 변환규칙에 의해 num2에 저장된 값도 double형으로 자동 형변환이 된다. 즉 위의 문장은 아래와 같은 형태로 형 변환이  한 차례 더 진행된다.

 

num3 = 32.0/7.0; 

 

<예제 2>

 

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

struct person
{
	char name[20];
	char phoneNum[20];
	int age;
};

int main(void)
{
	struct person man1, man2;
	strcpy(man1.name, "안성준");
	strcpy(man1.phoneNum, "010-1122-3344");
	man1.age = 23;

	printf("이름 입력: "); scanf("%s", man2.name);
	printf("번호 입력: "); scanf("%s", man2.phoneNum);
	printf("나이 입력: "); scanf("%d", &man2.age);

	printf("이름: %s\n", man1.name);
	printf("번호: %s\n", man1.phoneNum);
	printf("나이: %d\n", man1.age);

	printf("이름: %s\n", man2.name);
	printf("번호: %s\n", man2.phoneNum);
	printf("나이: %d\n", man2.age);
	return 0;
}

 

strcpy(man1.name, "안성준"); strcpy 함수를 이용해 문자열을 복사해 저장하고 있다.

 

<구조체 정의와 변수의 선언>

 

struct point
{
	int xpos;
	int ypos;
}pos1, pos2, pos3;
--------------------------------------------------------------------
struct person
{
	int age;
	char name[10];
};
struct point pos1, pos2, pos3;

 

위 코드 블록의 첫 번째 point 구조체처럼 구조체를 정의함과 동시에 변수를 선언할 수 있다. 밑의 person 구조체의 정의 및 선언과 결과적으로 동일하나 자주 쓰이지는 않는다.

 

<문제 22-1>

 

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

struct employee
{
	char name[10];
	char number[20];
	int salary;
};

int main(void)
{
	struct employee man;
	strcpy(man.name, "종업원");
	strcpy(man.number, "850507-0009910");
	man.salary = 50;

	printf("%s\n", man.name);
	puts(man.number);
	printf("%d", man.salary);

	return 0;
}

 

사용자가 입력한 정보로 위의 변수를 채우라는 조건에 맞지 않으므로 아래와 같이 코드를 수정해 주었다.

 

<문제의 조건에 맞는 코드>

 

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

struct employee
{
	char name[10];
	char number[20];
	int salary;
};

int main(void)
{
	struct employee man;
	scanf("%s", man.name);
	scanf("%s", man.number);
	scanf("%d", &man.salary);

	printf("%s\n", man.name);
	puts(man.number);
	printf("%d", man.salary);
	return 0;
}

 

puts함수는 출력 후 자동 개행이 이루어진다.

 

<구조체 변수의 초기화>

 

#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-0000-0000",21 };
	printf("%d %d\n", pos.xpos, pos.ypos);
	printf("%s %s %d\n", man.name, man.phoneNum, man.age);
	return 0;
}

 

int형과 같은 자료형의 변수를 선언과 동시에 초기화할 수 있듯이, 구조체 변수도 동시에 초기화할 수 있다. 그리고 초기화 방법은 배열의 초기화와 동일하다.

 

struct person man = { "이승", "010-0000-0000",21 };

초기화 과정에서는 문자열 저장을 위해 strcpy함수를 호출하지 않아도 된다.