Desc :

자료형의 실제 크기를 알 수 있다면

프로그래밍 과정에서 발생하는 스택 깨짐, 통신 loss 등 여러 문제에 대처할 수 있는 방법을 찾을 수 있음

 

class 크기가 다른 이유

컴퓨터 프로세서의 데이터 버스는 한 번에 8바이트 데이터를 담아 이동하는데

(64bit 운영체제에서 한 번에 처리할 수 있는 데이터의 양은 64bit, 즉 8byte이다.)

4바이트 단위로 몇 번 움직이느냐에 따라 sizeof의 결과가 달라진다

 

클래스 Temp는 int 4바이트 + bool 1바이트 = 5바이트지만

데이터 버스는 한 번 이동하여 결과가 8바이트가 됨

 

클래스 Temp1는 int 4바이트 +double 8바이트 = 12바이트지만

데이터 버스는 두 번 이동하여 결과가 16바이트가 됨

 


Source Code :

#include <iostream>

using namespace std;

class Temp{
	int no;
	bool is_on;
};
class Temp1 {
	int no;
	double db;
};

int main()
{
	cout << "char 크기 : " << sizeof('p') << endl;
	cout << "int 크기 : " << sizeof(10) << endl;
	cout << "double 크기 : " << sizeof(10.0) << endl;
	cout << "클래스 크기 : " << sizeof(Temp) << endl;
	cout << "클래스 크기 : " << sizeof(Temp1) << endl;

	return 0;
}

 


Result :

'C++' 카테고리의 다른 글

[C++] 034 중첩 순환문 for ~ continue ~ break  (0) 2021.03.18
[C++] 032, 033 중첩 조건문 if ~ else if ~ else  (0) 2021.03.18
[C++] 030 명시적 변환  (0) 2021.03.18
[C++] 029 캐스트 연산자  (0) 2021.03.18
[C++] 028 비트 연산자  (0) 2021.03.18

Desc :

 

C에서는 ()연산자에 변환할 자료형의 이름을 사용해 형 변환 (float)i1 / i2

 

C++ 에서는 C-style cast를 다음과 같이 사용할 수 있다  float(i1)

 

C-style cast는 컴파일 시간에 검사되지 않으므로 오용될 수 있다. (const를 제거하는 등)

그러므로 C-style cast는 일반적으로 피하는 게 좋다.



출처: https://boycoding.tistory.com/177 [소년코딩]

Source Code :

#include <iostream>

using namespace std;

int main()
{
	int number1 = 65;
	double number2 = 23.4;

	int number3 = int(number2);
	double number4 = double(number1 / number2);

	char ch = char(number1);

	cout << "number1 : " << number1 << endl;
	cout << "number2 : " << number2 << endl;
	cout << "number3 : " << number3 << endl;
	cout << "number4 : " << number4 << endl;
	cout << "ch : " << ch << endl;

	return 0;
}

 


Result :

'C++' 카테고리의 다른 글

[C++] 032, 033 중첩 조건문 if ~ else if ~ else  (0) 2021.03.18
[C++] 자료형의 크기 sizeof  (0) 2021.03.18
[C++] 029 캐스트 연산자  (0) 2021.03.18
[C++] 028 비트 연산자  (0) 2021.03.18
[C++] 027 쉼표 연산자  (0) 2021.03.18

Desc :

어떤 자료형을 다른 자료형으로 변경하는 방법

 

C언어 스타일의 형변환 ( 자료형 )

- 아무 조건도 없이 무작정 변경 --> 에러발생시 디버깅어려움

 

C++ 형변환

static_cast <> : 가장 기본적인 캐스트 연산 방법

dynaminc_cast <> :  객체지향 언어의 다형성을 이용하여 모호한 타입 캐스팅 오류를 막아줌

const_cast <> : 자료형이 갖고 있는 상수 속성을 제거

reinterpret_cast <> : 어떠한 포인터 타입끼리도 변환할 수 있게 도움

 

 


Source Code :

#include <iostream>

using namespace std;

int main()
{
	int x = 2;
	double y = 4.4;

	int i = static_cast<int>(y / x);	//Cpp style --> 연산한 값을 형변환
	int j = (int)y / x;			// C style --> 형변환한 y값과 연산
	double k = y / x;

	cout << "4.4 / 2 = (static_cast<int>) " << i << endl;
	cout << "4.4 / 2 = (int) " << j << endl;
	cout << "4.4 / 2 = " << k << endl;

	return 0;
}

 


Result :

'C++' 카테고리의 다른 글

[C++] 자료형의 크기 sizeof  (0) 2021.03.18
[C++] 030 명시적 변환  (0) 2021.03.18
[C++] 028 비트 연산자  (0) 2021.03.18
[C++] 027 쉼표 연산자  (0) 2021.03.18
[C++] 026 조건부 삼항 연산자  (0) 2021.03.18

Desc :

#include <bitset>

C++에서는 char, int로 비트연산을 하는 것보다 bitset이라는 컨테이너를 사용하는 것이 수월함

 

bitset<8> bit1

크기가 8비트인 변수를 선언

 

bit1.reset()

비트세트를 0으로 초기화


Source Code :

#include <iostream>
#include <bitset>

using namespace std;

int main()
{
	bitset<8> bit1;
	bit1.reset();	// 0000 0000
	bit1 = 127;		// 0111 1111

	bitset<8> bit2;
	bit2.reset();
	bit2 = 0x20;	// 32

	bitset<8> bit3 = bit1 & bit2;
	bitset<8> bit4 = bit1 | bit2;
	bitset<8> bit5 = bit1 ^ bit2;
	bitset<8> bit6 = ~bit1;
	bitset<8> bit7 = bit2 << 1;
	bitset<8> bit8 = bit2 >> 1;

	cout << "bit1 & bit2 : " << bit3 << ", " << bit3.to_ulong() << endl;
	cout << "bit1 | bit2 : " << bit4 << ", " << bit4.to_ulong() << endl;
	cout << "bit1 ^ bit2 : " << bit5 << ", " << bit5.to_ulong() << endl;
	cout << "~bit1 : " << bit6 << ", " << bit6.to_ulong() << endl;
	cout << "bit2 << 1  : " << bit7 << ", " << bit7.to_ulong() << endl;
	cout << "bit2 >> 1 : " << bit8 << ", " << bit8.to_ulong() << endl;

	return 0;
}

 


Result :

'C++' 카테고리의 다른 글

[C++] 030 명시적 변환  (0) 2021.03.18
[C++] 029 캐스트 연산자  (0) 2021.03.18
[C++] 027 쉼표 연산자  (0) 2021.03.18
[C++] 026 조건부 삼항 연산자  (0) 2021.03.18
[C++] 020 논리형 변수  (0) 2021.01.24

Desc :

 

쉼표 연산자는 비슷한 의미의 코드를 이어 붙이는데 사용된다.

 

변수를 여러번 이어 붙여 한번에 변수를 선언하고 초기화

(가독성 문제로 지양하는 방식이긴 함)

 

 


Source Code :

#include <iostream>

using namespace std;

int main()
{
	int apple = 1000, banana = 2000, carrot = 500;

	printf("과일 채소 가격\n");
	printf("사과 :  %d원 , 바나나 : %d원, 당근 : %d원 \n", apple, banana, carrot);

	return 0;
}

 


Result :

'C++' 카테고리의 다른 글

[C++] 029 캐스트 연산자  (0) 2021.03.18
[C++] 028 비트 연산자  (0) 2021.03.18
[C++] 026 조건부 삼항 연산자  (0) 2021.03.18
[C++] 020 논리형 변수  (0) 2021.01.24
[C++] 019 실수형 변수  (0) 2021.01.24

Desc :

 

간단한 if문을 한 줄로 대체할 수 있는 연산자 (코드 최적화)

 

if (x>y)           

z=x;

else              

z=y;

z = x>y? x : y;

 

조건 ? true : false

 


Source Code :

#include <iostream>

using namespace std;

int main()
{
	int x = 1;
	int y = 2;
	int z = 0;

	z = x > y ? x : y;

	cout << "x와 y중 더 큰 값은 : " << z << endl;

	return 0;
}

 


Result :

'C++' 카테고리의 다른 글

[C++] 028 비트 연산자  (0) 2021.03.18
[C++] 027 쉼표 연산자  (0) 2021.03.18
[C++] 020 논리형 변수  (0) 2021.01.24
[C++] 019 실수형 변수  (0) 2021.01.24
[C++] 018 정수형 변수  (0) 2021.01.24

Desc :

 

 


Source Code :

#include <stdio.h>
#include <winsock2.h>

#pragma comment(lib,"wsock32.lib")

void main()
{
	SOCKET s;	// 소켓 디스크립터
	WSADATA wsaData;
	SOCKADDR_IN sin;	// 소켓 구조체

	if (WSAStartup(WINSOCK_VERSION, &wsaData) != 0)
	{
		printf("WSAStartup 실패, 에러코드 = %d\n", WSAGetLastError());
		return;
	}

	s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);	// TCP/IP용 소켓 생성

	if (s == INVALID_SOCKET)
	{
		printf("소켓 생성 실패, 에러코드: %d \n", WSAGetLastError());
		WSACleanup();	//WS2_32.DLL의 사용을 종료합니다
		return;
	}

	sin.sin_family = AF_INET;	// 주소 체계 설정
	sin.sin_addr.s_addr = inet_addr("127.0.0.1");	// 접속 주소 설정
	sin.sin_port = htons(2001);	// 포트 번호 설정

	if (connect(s, (struct sockaddr*)&sin, sizeof(sin)) != 0)
	{
		printf("접속 실패, 에러코드 = %u \n", WSAGetLastError());
		closesocket(s);
		WSACleanup();
		return;
	}

	if (closesocket(s) != 0)
	{
		printf("소켓 제거 실패, 에러코드 = %u \n", WSAGetLastError());
		WSACleanup();
		return;
	}

	if (WSACleanup() != 0)
	{
		printf("WSACleanup 실패, 에러코드 = %u \n", WSAGetLastError());
		return;
	}

	puts("127.0.0.1의 2001번 포트에 접속을 성공하였습니다.");
}

 


Result :

10061 대상컴퓨터에서 연결을 거부했다.............

'C' 카테고리의 다른 글

[C] TCP/IP 초기화하기  (1) 2021.02.18
[C] 268 주소록 (아직 작성 안함)  (0) 2021.02.18
[C] 267 이중 링크드 리스트 구현하기  (1) 2021.02.17
[C] 266 단일 링크드 리스트 구현  (0) 2021.02.17
[C] 265 큐 구현  (0) 2021.02.17

Desc :

TCP/IP - 프로그램에서 원거리의 컴퓨터와 상호 데이터를 주고받기 위한 통신 규약

TCP/IP 통신 프로그램은 흔히 소켓 프로그램이라고도 한다

 

TCP/IP를 통해 데이터를 주고 받으려면

파일을 입출력 할 때 처럼

소켓의 개방 - socket()

소켓의 제거 - closesocket() 함수가 반드시 필요

 

윈도우 소켓 프로그램에서는 여러 종류의 소켓 버전이 사용되기 때문에

소켓 버전을 설정 - WSAStartup()

해제 - WSAClean() 함수도 필수적

 

TCP/IP에 사용되는 모든 함수들은 <winsock2.h>에 선언되어 있다

일반적인 C Runtime Library 가 아니기 때문에

wsock32.lib를 반드시 포함

#pragma comment (특정 라이브러리 파일을 포함시킬 때 사용)

 

 

 

 

소켓 디스크립터: 소켓을 개방, 송수신, 종료할 때 사용

WSADATA wsaData: 현재 사용 가능한 윈속 정보를 얻기 위해 정의, 소켓버전 값 저장됨

 


Source Code :

#include <stdio.h>
#include <winsock2.h>

#pragma comment(lib,"wsock32.lib")

void main()
{
	SOCKET s;	// 소켓 디스크립터
	WSADATA wsaData;

	if (WSAStartup(WINSOCK_VERSION, &wsaData) != 0)
	{
		printf("WSAStartup 실패, 에러코드 = %d\n", WSAGetLastError());
		return;
	}
    
	puts(wsaData.szDescription); 	// 사용하고있는 윈속 버전
	puts(wsaData.szSystemStatus);	// 사용하고있는 윈속의 상태

	s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);	// TCP/IP용 소켓 개방

	if (s == INVALID_SOCKET)
	{
		printf("소켓 생성 실패, 에러코드: %d \n", WSAGetLastError());
		WSACleanup();	//WS2_32.DLL의 사용을 종료합니다
		return;
	}

	if (closesocket(s) != 0)	// 소켓 제거
	{
		printf("소켓 제거 실패, 에러코드 = %u \n", WSAGetLastError());
		WSACleanup();	//WS2_32.DLL의 사용을 종료합니다
		return;
	}

	if (WSACleanup() != 0)	// 소켓에서 사용했던 자원들 비우기
	{
		printf("WSACleanup 실패, 에러코드 = %u \n", WSAGetLastError());
		return;
	}

	puts("윈속을 사용할 수 있습니다.");
}

 


Result :

Desc :

 

 


Source Code :

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

int add_list(char* name);
void print_list(void);
void remove_list(void);

typedef struct tagLinkedList
{
	char name[30];

	struct tagLinkedList *prev;
	struct tagLinkedList *next;
}ADDR;

ADDR *g_pAddrHead = NULL;

void main()
{
	add_list("Kim");
	add_list("Choi");

	print_list();
	remove_list();
}

int add_list(char* name)
{
	ADDR *plocal;

	if (g_pAddrHead == NULL)
	{
		g_pAddrHead = malloc(sizeof(ADDR));

		if (g_pAddrHead == NULL)
		{
			return 0;	// 할당실패
		}

		g_pAddrHead->prev = NULL;
		g_pAddrHead->next = NULL;
	}
	else
	{
		plocal = malloc(sizeof(ADDR));

		if (plocal == NULL)
		{
			return 0; // 할당 실패
		}
		
		g_pAddrHead->next = plocal;
		plocal->prev = g_pAddrHead;
		g_pAddrHead = plocal;
		g_pAddrHead->next = NULL;
	}

	strcpy(g_pAddrHead->name, name);

	return 1;
}

void print_list(void)
{
	int count = 1;
	ADDR *plocal;

	plocal = g_pAddrHead;

	while (plocal->prev) //리스트의 맨 처음으로 이동
	{
		plocal = plocal->prev;
	}

	while (plocal)
	{
		printf("No.%d: ", count++);
		puts(plocal->name);
		plocal = plocal->next;
	}
}

void remove_list(void)
{
	ADDR *plocal;	// 다음 노드 주소 저장

	while (g_pAddrHead->prev) // 리스트 맨 처음으로 이동
	{
		g_pAddrHead = g_pAddrHead->prev;
	}
	
	while (g_pAddrHead)	// 마지막 노드까지 메모리 반환
	{
		plocal = g_pAddrHead->next;

		free(g_pAddrHead);	// 현재 노드 메모리 반환 

		g_pAddrHead = plocal;
	}

	g_pAddrHead = NULL; // 재사용을 위한 초기화
}

조건문에서 == 연산자를 =로 썼다. 바보...


Result :

'C' 카테고리의 다른 글

[C] TCP/IP 초기화하기  (1) 2021.02.18
[C] 268 주소록 (아직 작성 안함)  (0) 2021.02.18
[C] 266 단일 링크드 리스트 구현  (0) 2021.02.17
[C] 265 큐 구현  (0) 2021.02.17
[C] 264 스택구현  (0) 2021.02.17

+ Recent posts