char ** Ptr;
char apple[15];
char cake[15];
Ptr = new char*[2];
Ptr[0]=apple;
Ptr[1]=cake;
可惜更新后Ptr[1]
,Ptr[0]
变成cake
除了Ptr[1]
。我很确定问题是我如何声明Ptr
我本质上希望它是一个字符串数组。有没有办法在我保留的地方做到这一点char ** Ptr
?
编辑:
{
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
(呜呜声)。任何帮助将不胜感激。
无论如何,感谢您的时间。