I don't understand passing pointer between classes.
hasArray.cpp geneartes an array, then returns a pointer of the start of that array.
Main.cpp declares hasArray.cpp
Compiling:
g++ -c hasArray.cpp
g++ -c Main.cpp
g++ Main.o hasArray.o -o output
Output:
Inside main
Inside hasArray
Pointer: 0x7fff5ccd7a70
Array: 1, 2, 3, 4, 5,
Pointer: 0x7fff5ccd7a70
Array: 2063291128, 32767, 49454805, 1, 2063291128,
The pointer address is passed between classes (as I expected), however the value at the pointer locations changed. I thought the point of passing a pointer is to reference the (same) memory. Why dose the data at that memory address change?
Thanks
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;
}