使用char **,其中新元素覆盖以前的元素

时间:2012-11-30 17:22:19

标签: c++ arrays pointers

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(woops)。不过,任何帮助都会非常感激。

无论如何,谢谢你的时间。

2 个答案:

答案 0 :(得分: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显然不再是指针,但为了清楚起见,我将变量和代码结构的名称保持相同。

答案 1 :(得分:-3)

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