인프런 커뮤니티 질문&답변
[배열을 레퍼런스로 보내는 것]
해결된 질문
작성
·
228
0
안녕하세요?
printArray함수에서 배열을 레퍼런스로 받으려고하면
void printArray(const int (&myArr)[10], const unsigned& length);
이렇게 선언 해줄 때
const int (&myArr)[10]
여기 10은 그냥 항상 하드코딩 해줘야하는거죠?
감사합니다.
<코드>
// 6_4.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
using namespace std;
void printArray(const int (&myArr)[10], const unsigned& length);
void selectionSort(int myArr[], const unsigned& length);
void swap(int& x, int& y);
int main()
{
int myArr[] = { 22, 13, 17, 26, 2, 11, 1, 5, 3, 7 };
unsigned length = sizeof(myArr) / sizeof(myArr[0]);
cout << length << endl;
printArray(myArr, length);
cout << "after selection sorting " << endl;
selectionSort(myArr, length);
cout << endl;
printArray(myArr, length);
return 0;
}
void printArray(const int (&myArr)[10], const unsigned& length)
{
for (unsigned i = 0; i < length; ++i)
{
cout << myArr[i] << " ";
}
cout << endl;
}
void selectionSort(int myArr[], const unsigned& length)
{
for (unsigned i = 0; i < length - 1; ++i)
{
int min_idx = i;
for (unsigned j = i + 1; j < length; ++j)
{
if (myArr[min_idx] > myArr[j])
{
min_idx = j;
}
}
swap(myArr[min_idx], myArr[i]);
}
}
void swap(int& x, int& y)
{
int temp = x;
x = y;
y = temp;
}
// 6_4.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
using namespace std;
void printArray(const int (&myArr)[10], const unsigned& length);
void selectionSort(int myArr[], const unsigned& length);
void swap(int& x, int& y);
int main()
{
int myArr[] = { 22, 13, 17, 26, 2, 11, 1, 5, 3, 7 };
unsigned length = sizeof(myArr) / sizeof(myArr[0]);
cout << length << endl;
printArray(myArr, length);
cout << "after selection sorting " << endl;
selectionSort(myArr, length);
cout << endl;
printArray(myArr, length);
return 0;
}
void printArray(const int (&myArr)[10], const unsigned& length)
{
for (unsigned i = 0; i < length; ++i)
{
cout << myArr[i] << " ";
}
cout << endl;
}
void selectionSort(int myArr[], const unsigned& length)
{
for (unsigned i = 0; i < length - 1; ++i)
{
int min_idx = i;
for (unsigned j = i + 1; j < length; ++j)
{
if (myArr[min_idx] > myArr[j])
{
min_idx = j;
}
}
swap(myArr[min_idx], myArr[i]);
}
}
void swap(int& x, int& y)
{
int temp = x;
x = y;
y = temp;
}
감사합니다.
답변 1
1
홍정모
지식공유자
포인터 연산을 하려면 사이즈를 알아야 해서 하드코딩 해야만 합니다.
이건 C언어 문법에서 자세히 다루는 내용입니다.
C++에서는 직접 배열을 사용하기 보다는 컨테이너를 쓰지요.





