-1
클래스 사이에 포인터를 전달하는 것을 이해하지 못합니다.클래스 사이에 전달한 후의 포인터 값
hasArray.cpp는 배열을 만든 다음 해당 배열의 시작 부분에 대한 포인터를 반환합니다.
하여 Main.cpp는 hasArray.cpp를 선언
컴파일 :
g++ -c hasArray.cpp
g++ -c Main.cpp
g++ Main.o hasArray.o -o output
출력 :
포인터 주소 (I 예상대로) 클래스 사이에 전달되는Inside main
Inside hasArray
Pointer: 0x7fff5ccd7a70
Array: 1, 2, 3, 4, 5,
Pointer: 0x7fff5ccd7a70
Array: 2063291128, 32767, 49454805, 1, 2063291128,
, 그러나 가치 포인터 위치가 변경되었습니다. 나는 포인터를 전달하는 것이 (동일한) 메모리를 참조하는 것이라고 생각했다. 왜 메모리 주소의 데이터가 변경됩니까?
감사
hasArray.cpp
#include <stdio.h>
#include <iostream>
#include "hasArray.h"
using namespace std;
int * hasArray::passPointer(){
cout << "Inside hasArray\n";
int array[5] = {1,2,3,4,5};
int * pointer = &array[0];
cout << "Pointer: " << pointer<< "\n";
cout << "Array: ";
for(int i =0 ; i < 5; i++)
cout << array[i] << ", ";
cout << "\n";
return pointer;
}
hasArray.hpp
#ifndef _HASARRAY_H_
#define _HASARRAY_H_
#include <stdio.h>
#include <iostream>
class hasArray{
public:
// hasArray();
int * passPointer();
};
#endif
하여 Main.cpp
#include <stdio.h>
#include <iostream>
#include "hasArray.h"
using namespace std;
int main(){
cout << "Inside main\n";
hasArray x;
int * pointer = x.passPointer();
cout << "Pointer: " << pointer << "\n";
cout << "Array: ";
for(int i =0 ; i < 5; i++)
cout << pointer[i] << ", ";
return 0;
}
일반적인 주석으로, 원시 포인터가 아닌 C++에서 객체, 참조 및 스마트 포인트를 사용해야합니다. – crazyGuy