๐Ÿ“ Coding Test Study/C++

C++ ๋™์ ํ• ๋‹น?

ibelieveinme 2021. 3. 27. 14:52
728x90

* ๋ฐฐ์—ด์˜ ๊ธธ์ด๋ฅผ ๊ณ ์ •ํ•œ๋‹ค๋Š” ๊ฒƒ๊ณผ ๋™์ ํ• ๋‹นํ•œ๋‹ค๋Š” ๊ฒƒ์˜ ์ฐจ์ด์ ์€?

- ๊ณ ์ •๋ฐฐ์—ด(fixed array): ์ปดํŒŒ์ผ ํƒ€์ž„์— ๋ฐฐ์—ด์˜ ๊ธธ์ด๋ฅผ ์ •ํ•˜๋Š” ๊ฒƒ.

- ๋™์ ๋ฐฐ์—ด(dynamically array): ๋Ÿฐํƒ€์ž„ ๋™์•ˆ์— ๋ฐฐ์—ด์˜ ๊ธธ์ด๋ฅผ ์ •ํ•˜๋Š” ๊ฒƒ.

 

* ๋™์ ํ• ๋‹น์„ ์œ„ํ•ด ํ•„์š”ํ•œ ์—ฐ์‚ฐ์ž: new[], delete[]

 

* ๋ฐฐ์—ด์˜ ๊ธธ์ด๋ฅผ ๋™์ ์œผ๋กœ ํ• ๋‹นํ•˜๊ณ  ๊ฐ’์„ ์ดˆ๊ธฐํ™”์‹œ์ผœ๋ณด์ž.

#include <iostream>

int main(){
    int length;
    cin >> length;
    
    int *array = new int[length]; //์ด๋ ‡๊ฒŒ ํ•˜๋ฉด ๋ฐฐ์—ด์˜ ๊ธธ์ด๋ฅผ ์ž…๋ ฅ๋ฐ›์€ length๋กœ ํ• ๋‹น ๊ฐ€๋Šฅ
    
    for(int i = 0; i<length; i++){//ํ• ๋‹น๋ฐ›์€ ๊ธธ์ด์•ˆ์— ๊ฐ’ ๋„ฃ์–ด์ฃผ๊ธฐ.
    	cin >> array[i];
    }
    
    delete[] array;// ๋™์ ํ• ๋‹น ์‹œ, ๋ฐฐ์—ด ํ• ๋‹นํ•œ ๋ฉ”๋ชจ๋ฆฌ ๊ผญ ํ•ด์ œํ•ด์ฃผ๊ธฐ.
    
    return 0;
}

 

* ๋ฐฐ์—ด์˜ ๊ธธ์ด๋ฅผ ๋™์ ์œผ๋กœ ํ• ๋‹นํ•˜๊ณ  ํ•จ์ˆ˜๋กœ ์ „๋‹ฌํ•ด์„œ ์ตœ๋Œ€๊ฐ’์„ ์ฐพ์•„๋ณด์ž

#include <iostream>
using namespace std;

void findMax(int *arr);

int main() {
	int length;
	cin >> length;

	int *arr = new int[length];
	for (int i = 0; i < length; i++) {
		cin >> arr[i];
	}
	findMax(arr);
	delete[] arr;

	return 0;
}

void findMax(int *arr) {
	int max = arr[0];
	for (int i = 1; i < sizeof(arr); i++) {
		if (arr[i] > max) {
			max = arr[i];
		}
	}
	cout << max;
}

cf) ๋ฐฐ์—ด์˜ ๊ธธ์ด๋ฅผ ์•Œ๊ณ  ์‹ถ์„ ๋•? sizeof() ์—ฐ์‚ฐ์ž ์‚ฌ์šฉ!

 

728x90