2013-02-07 32 views
0

我在我的函數中取消了一個指向我的數組結構的指針並將其打印在函數中。這工作正常,但是,只要我將指針從不正確打印的函數返回。我對類似問題做了一些研究,但我似乎無法找到我確切的問題。傳遞指針後數組數據被破壞,C

正確的打印:11 5 1 2 3 4 5 10 20 30 40 不正確:11 5 1 2 5024 96 0 0 20 30 40

(問題區域是在CAPS註釋)

[ arraytools.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; 
} 

[main.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

這被標記'C',但你目前'C++代碼'。這兩個真的是不同的語言...... – StoryTeller

回答

3

此行是問題的根本:

short int newarray[size]; 

它分配在堆疊陣列,然後返回該地址,即使你從這個函數返回變得儘快無效。試試這個:

short *newarray = new short [size]; 

現在它進入堆。當然,你也應該刪除,與刪除[]操作,當你不再需要它,就像也許在主要印刷後:

delete[] nptr; 
+0

這固定了nug,謝謝!我認爲這是我的指針表示法的問題。 – Ktmock13

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 
2

當您將新數組作爲本地函數的變量時,它將分配在堆棧上(通常)。然後你返回一個指向調用代碼的指針。但是一旦方法返回,內存就會被釋放。所以一旦被調用的函數返回,指針就指向一個未定義的內存區域。

1

你的函數返回一個指向本地變量的指針,它存儲在堆棧中。你的數據需要malloc內存。