2012-11-30 38 views
2
char ** Ptr; 
char apple[15]; 
char cake[15]; 
Ptr = new char*[2]; 

Ptr[0]=apple; 
Ptr[1]=cake; 

更新Ptr[1]後,不幸的是新的元素,Ptr[0]成爲除了Ptr[1]cake。我很確定問題在於我如何聲明Ptr我基本上希望它是一個字符串數組。有沒有辦法做到這一點,我保持char ** Ptr使用char **其中覆蓋以前的元素

編輯:

{ 
char **Ptr; 
{ 
char apple[15]; 
Ptr = new char*[2]; 
for(int k=0;k<2;k++) 
{ 
memset(apple,0,15); 
//apple= 
Ptr[k]=apple; //Note that apple in fact changes everytime 
} 
//Originally I had Ptr[k]=apple but it seemed I was merely copying the address of 
//apple which works great except when I leave the scope trying to call it the addr no 
//longer exists and I was getting lucky the last entry showed up at all. So I then 
//figured I would use 

strcpy(Ptr[k],apple); 

//I then checked the value for both was correct even when I deleted apple. 
// Finally I leave the scope where all this is taking place 
} 
cout<<Ptr[0]; 
cout<<Ptr[1]; 
} 

幸運的是,他們實際上相當於垃圾。前幾個字符是相同的,但大多是垃圾。我想可能是Ptr的範圍問題,所以基本上使它成爲全球同樣的問題。無論如何,我留下了原來的問題,即使它沒有包含任何問題,因爲我已經做出了單獨的變量cake(woops),因爲每個人都非常善意指出。任何幫助將不勝感激,但。

無論如何,謝謝你的時間。

+2

[Works fine here](http://ideone.com/nKTsd7)。 –

+0

你能告訴我們你是如何解除引用'Ptr'來查看它的內容嗎? –

+1

問題不在這裏明顯 –

回答

0

即使你的編輯它仍然不是很清楚你的意思後,特別是因爲它看起來,你明白指針和範圍是。

更長時間的存在,我幸運地出現了最後一個條目。所以我當時 想我會用

strcpy(Ptr[k],apple); 

如果使用strcpy這裏,那麼你必須分配的內存堆上Ptr[k]。那麼你的代碼將工作得很好。

但是,更好的是使用C++功能。即,而不是分配的chars數組和指針到chars,這是一個C的方法,使用下列:

vector<string> Ptr; 
{ 
    string apple; 
    for(int k=0;k<2;k++) 
    { 
     //apple= 
     Ptr.push_back(apple); 
    } 
} 
cout<<Ptr[0]; 
cout<<Ptr[1]; 

在這裏,我離開變量和碼結構的名稱是爲了清楚起見,相同的,雖然Ptr顯然不再是一個指針。

-3

使用Ptr = malloc(sizeof(char *) * 2);在替換的Ptr = new char*[2];

+5

真的爲什麼malloc? –