0

我在我的函数中取消引用指向我的数组结构的指针并在函数中打印它。但是,这可以正常工作,只要我将指针从函数中返回,它就会错误地打印出来。我对类似问题进行了一些研究,但我似乎无法找到我的确切问题。

正确打印:11 5 1 2 3 4 5 10 20 30 40 错误:11 5 1 2 5024 96 0 0 20 30 40

(问题区域在 CAPS 中注释)

[数组工具.cpp]

#include "arraytools.h"
#include <iostream>

using namespace std;

void DisplayArray (short int* a)
{
    short int size = a[0];
    int i;
    for (i=0; i<size; i++)
    {
        cout<< a[i] << " ";
    }
    cout<<endl;
}

short int* ConcatArray (short int* a1, short int* a2)
{
    short int size = a1[0] + a2[0] + 1;  //size of newarray
    short int *ptr;          //pointer for newarray
    short int newarray[size];  //initializing new array with given new size
    newarray[0] = size;    //making first object in new array the size of it

    int i,j;    
    for (i=0; i<a1[0]; i++)  //loop to store first array objects to newarray
    {
        newarray[i+1] = a1[i];
    }

    int lastpoint = a1[0] + 1;  //marks the point to start adding the second array to newarray
    for (j=0; j<a2[0]; j++)  //loop to store second array objects to newarray
    {
        newarray[lastpoint] = a2[j];
        lastpoint++;

    }

    ptr = &newarray[0];  //assigning new array to pointer
    DisplayArray(ptr);  //PRINTS CORRECTLY HERE
    return ptr;
}

[主.cpp]

#include "arraytools.h"
#include <iostream>
using namespace std;

int main()
{
    char choice = 'y';  //user defined later in program
    while (choice == 'y') // for repeating process
    {
        //declaring two arrays of short int
        short int arr1[] = {5,1,2,3,4};
        short int arr2[] = {5, 10, 20, 30, 40};

        //pointers to refer to declared arrays
        short int* nptr, *ar1, *ar2;

        ar1 =arr1;
        ar2 =arr2;

        DisplayArray(ar1);
        DisplayArray(ar2);

        nptr = ConcatArray(ar1, ar2); //RECIEVES RETURNED POINTER
        DisplayArray(nptr);  //PRINTS INCORRECTLY

        cout<<"Run process again? y/n: "; //loop exit condition
    cin >> choice;
    }
   return 0;
}
4

4 回答 4

4

您正在“在堆栈上”分配 newarray。一旦超出范围(即函数结束),它将被回收。如果您真的想这样做,请使用 malloc。或者,如果您真的在使用 C++,请考虑使用更好的容器,例如 std::vector。

ConcatArray (short int* a1, short int* a2)
{
    short int size = a1[0] + a2[0] + 1;  //size of newarray
    short int *ptr;          //pointer for newarray
    short int newarray[size];  //initializing new array with given new size
于 2013-02-07T20:48:44.583 回答
4

这一行是问题的根源:

short int newarray[size];

它在堆栈中分配数组,然后返回它的地址,即使从该函数返回后它就变得无效。试试这个:

short *newarray = new short [size];

现在它进入堆。当然,当您不再需要它时,您还应该使用 delete[] 运算符将其删除,例如打印后可能在 main 中:

delete[] nptr;
于 2013-02-07T20:53:47.863 回答
2

当您将新数组作为函数的局部变量时,它会分配在堆栈上(通常)。然后返回一个指向调用代码的指针。但是一旦方法返回,内存就会被释放。因此,一旦被调用函数返回,指针就会指向未定义的内存区域。

于 2013-02-07T20:48:49.747 回答
1

您的函数返回存储在堆栈中的局部变量上的指针。您的数据需要 malloc 内存。

于 2013-02-07T20:49:20.740 回答