C++_3주차_정리

728x90

1. 정적할당, 동적할당 

#include <iostream> //c++의 표준 입출력 헤더파일(cin, cout객체 포함)
using namespace std; //이름 공간 설정 
#include<string>

int main() {
	int* ptr1 = new int; //1개의 int형 공간 동적할당하여 포인터로 그 주소 지칭
	int* ptr10 = new int[10]; //10개의 int형 공간 동적할당 

	*ptr1 = 50;
	cout << "Value" << *ptr1 << endl;
	delete ptr1; //반환

	for (int i = 0; i <= 9; i++) {
		ptr10[i] = 50 + i;
	}
	cout << endl;
	for (int i = 9; i >= 0; i--) {
		cout << "Value of ptr10[" << i << "J = " << ptr10[i] << endl;
	}
	delete[] ptr10;//배열 공간은 []표시

	getchar();
	return 0;
}

 

2. 구조체 사용하기 

-구조체타입 변수, 배열, 포인터 선언 

-구조체변수로 내부 멤버 지칭 시 (.)도트 연산자 사용 

-구조체포인터로 내부 멤버 지칭 시 ->연산자 사용 

#include <iostream> //c++의 표준 입출력 헤더파일(cin, cout객체 포함)
using namespace std; //이름 공간 설정 
#include<string>

typedef struct student { //학생의 구조체 타입으로 데이터 묶음
	int ID;
	int age;
	char name[30];
	double GPA;
}student;
int main() {
	student st1;
	student st2;
	student st3 = { 20123, 22, "Kevin", 4.0 };

	//구조체 배열 초기화 동시에 선언 
	student st4[4] = { {20345, 23, "hong", 2.2},
		{20456, 22, "park", 2.1}, {20567, 23, "Lee", 2.3}, {20567, 25, "cho", 2.4 } };

	//구조체형 포인터 변수 -> 
	student* ptr_st1, * ptr_st4;
	
	ptr_st1 = &st1;
	cout << ptr_st1->ID << endl;

	st1.ID = 20234;
	st1.age = 21;
	strcpy(st1.name, "Michael");
	st1.GPA = 4.2;
	getchar();
	return 0;
}

728x90

'C++, C언어 > [문법]_C++' 카테고리의 다른 글

C++_5주차_정리  (0) 2021.12.20
C++_4주차_정리  (0) 2021.12.20
C++_2주차_정리  (0) 2021.12.20
C++_1주차_정리  (0) 2021.12.20
C++ 객체지향프로그래밍_Ch04정리  (0) 2021.09.27