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

Using char ** where new elements overwriting previous elements

本文关键字:元素 覆盖 char 新元素 使用      更新时间:2023-10-16
char ** Ptr;
char apple[15];
char cake[15];
Ptr = new char*[2];
Ptr[0]=apple;
Ptr[1]=cake;

不幸的是,在更新Ptr[1]后,除了Ptr[1]之外,Ptr[0]变得cake。我很确定问题在于我如何声明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)。不过,任何帮助将不胜感激。

无论如何,感谢您的时间。

即使在编辑之后,仍然不太清楚你的意思,特别是因为你似乎确实理解了什么是指针和范围。

存在的时间更长,我很幸运最后一个条目出现了。所以我然后以为我会使用

strcpy(Ptr[k],apple);

如果您使用这样的strcpy,则必须为堆上的每个Ptr[k]分配内存,并且您的代码将正常工作。

但是,由于您使用的是C++编码,因此最好坚持使用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显然不再是指针。

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