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),因爲每個人都非常善意指出。任何幫助將不勝感激,但。
無論如何,謝謝你的時間。
[Works fine here](http://ideone.com/nKTsd7)。 –
你能告訴我們你是如何解除引用'Ptr'來查看它的內容嗎? –
問題不在這裏明顯 –