작성
·
111
·
수정됨
0
&array
이렇게 찍으면 나오는데 (int)&array
라고 쓰면 에러가 떠요.에러 내용은 아래와 같습니다:
% cd "/var/folders/4t/20bjrv5j34s9rpyghnxc36s80000gn/
T/" && g++ -std=c++17 tempCodeRunnerFile.cpp -o tempCodeRunnerFile && "/var/folders/4t
/20bjrv5j34s9rpyghnxc36s80000gn/T/"tempCodeRunnerFile
tempCodeRunnerFile.cpp:31:21: error: cast from pointer to smaller type 'int' loses information
cout << (int)&array[row][col] << '\t';
^~~~~~~~~~~~~~~~~~~~~
1 error generated.
아래는 강의예시를 그대로 따라한 코드입니다.
#include <iostream>
using namespace std;
int main()
{
const int num_rows = 3;
const int num_columns = 5;
for(int row = 0; row < num_rows; ++row)
{
for(int col = 0; col < num_columns; ++col)
{
cout << '[' << row << ']' << '[' << col << ']' << '\t';
}
cout << endl;
}
cout << endl;
// copy initialization
int array[num_rows][num_columns] =
{
{1, 2, 3, 4, 5}, // row 0
{6, 7, 8, 9, 10}, // row1
{11, 12, 13, 14, 15} // row2
};
for(int row = 0; row < num_rows; ++row)
{
for(int col = 0; col < num_columns; ++col)
{
cout << (int)&array[row][col] << '\t';
}
cout << endl;
}
cout << endl;
return 0;
}
컴파일러는 viscose 사용중입니다.
답변 1
0
안녕하세요, 인프런 AI 인턴이에요. 주소 값을 출력할 때 에러가 발생하는 상황입니다. 주소를 출력할 때에는 변수 앞에 & 기호를 붙여야 하는데, int& array 라고 쓰면 에러가 발생하는 이유는 int&는 “참조(reference)” 타입을 의미하는 것입니다. 따라서, int& array에서 array는 int의 참조를 가리키는 것이기 때문에 주소 연산을 할 필요가 없어서 에러가 발생한 것입니다.
해결책으로는 변수 앞에 & 기호를 붙이지 말고 그냥 array만 적어주시면 됩니다. 즉, (int)&array 대신에 array라고만 작성하면 됩니다. 이렇게 하면 배열의 주소를 출력할 수 있습니다.
아래는 수정된 코드입니다.
#include
using namespace std;
int main()
{
const int num_rows = 3;
const int num_columns = 5;
for(int row = 0; row < num_rows; ++row)
{
for(int col = 0; col < num_columns; ++col)
{
cout << '[' << row << ']' << '[' << col << ']' << '\t';
}
cout << endl;
}
cout << endl;
// copy initialization
int array[num_rows][num_columns] =
{
{1, 2, 3, 4, 5}, // row 0
{6, 7, 8, 9, 10}, // row1
{11, 12, 13, 14, 15} // row2
};
for(int row = 0; row < num_rows; ++row)
{
for(int col = 0; col < num_columns; ++col)
{
cout << &array[row][col] << '\t';
}
cout << endl;
}
return 0;
}
수정된 코드를 실행하면 배열의 주소가 정상적으로 출력될 것입니다. 추가적인 질문이 있으시면 언제든지 물어보세요. 즐거운 코딩 되세요!