C++ 类之间传递后的指针值

C++ 类之间传递后的指针值,c++,pointers,C++,Pointers,我不理解在类之间传递指针 hasArray.cpp生成一个数组,然后返回该数组开头的指针 Main.cpp声明hasArray.cpp #include <stdio.h> #include <iostream> #include "hasArray.h" using namespace std; int * hasArray::passPointer(){ cout << "Inside hasArray\n"; int array[5]

我不理解在类之间传递指针

hasArray.cpp生成一个数组,然后返回该数组开头的指针

Main.cpp声明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;
}
汇编:

g++ -c hasArray.cpp
g++ -c Main.cpp
g++ Main.o hasArray.o -o output
输出:

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.h”
使用名称空间std;
int*hasArray::passPointer(){

cout一旦程序退出函数,您声明数组的方式(静态分配)将被破坏

您希望通过动态内存分配来执行此操作。您可以如下所示为阵列动态分配内存:

int *array = new int[5]{1,2,3,4,5};
把这个还给我。
只需确保执行<代码>删除[]数组;< /代码>以释放分配的内存。

作为一般注释,您应该使用C++中的对象、引用和智能点而不是原始指针。
int *array = new int[5]{1,2,3,4,5};