-1

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;
}
whilej10
  • 73
  • 5
  • as a general comment, you should use objects, references and smart points in C++ rather than raw pointers. – crazyGuy Nov 29 '14 at 00:13

1 Answers1

3

The way you declared the array (static allocation) will be destroyed once the program is out of the function.

The way you would want to do it is through dynamic memory allocation. You can dynamically allocate memory for the array like this:

int *array = new int[5]{1,2,3,4,5};

And simply return this. Just make sure to do delete[] array; afterwards to free up the allocated memory.

snixtho
  • 185
  • 1
  • 6