2012-11-30 22 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? –