C++ 使用char**,其中新元素覆盖以前的元素
不幸的是,在更新C++ 使用char**,其中新元素覆盖以前的元素,c++,arrays,pointers,C++,Arrays,Pointers,不幸的是,在更新Ptr[1]之后,Ptr[0]除了Ptr[1]之外,还变成了cake。我很确定问题在于我如何声明Ptr我本质上希望它是一个字符串数组。在我保存char**Ptr的地方有没有办法做到这一点 编辑: { 字符**Ptr; { 焦苹果[15]; Ptr=新字符*[2]; 对于(int k=0;k使用Ptr=malloc(sizeof(char*)*2);替换Ptr=new char*[2];使用Ptr=malloc(sizeof(char*)*2);替换Ptr=new char*[2]
Ptr[1]
之后,Ptr[0]
除了Ptr[1]
之外,还变成了cake
。我很确定问题在于我如何声明Ptr
我本质上希望它是一个字符串数组。在我保存char**Ptr
的地方有没有办法做到这一点
编辑:
{
字符**Ptr;
{
焦苹果[15];
Ptr=新字符*[2];
对于(int k=0;k使用Ptr=malloc(sizeof(char*)*2);
替换Ptr=new char*[2];
使用Ptr=malloc(sizeof(char*)*2);
替换Ptr=new char*[2]
即使在编辑之后,仍然不太清楚您的意思,特别是因为您似乎确实理解指针和作用域是什么
时间更长了,我很幸运最后一个条目出现了。所以我
我想我会用
{
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];
}
如果您像这里一样使用strcpy,那么您必须为堆上的每个Ptr[k]
分配内存。这样您的代码就可以正常工作了
<>但是,最好是使用C++的特性。即,不是分配<代码>字符数组>代码>指针,而是指向<代码>字符s>代码>,这是一个C方法,使用如下:
strcpy(Ptr[k],apple);
向量Ptr;
{
串苹果;
对于(int k=0;k,即使在编辑之后,仍然不太清楚您的意思,特别是因为看起来您确实理解指针和作用域是什么
时间更长了,我很幸运最后一个条目出现了。所以我
我想我会用
{
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];
}
如果您像这里一样使用strcpy,那么您必须为堆上的每个Ptr[k]
分配内存。这样您的代码就可以正常工作了
<>但是,最好是使用C++的特性。即,不是分配<代码>字符数组>代码>指针,而是指向<代码>字符s>代码>,这是一个C方法,使用如下:
strcpy(Ptr[k],apple);
向量Ptr;
{
串苹果;
对于(int k=0;k.您能告诉我们您是如何取消引用Ptr
查看其内容的吗?问题显然不在这里。您能告诉我们您是如何取消引用Ptr
查看其内容的吗?问题显然不在这里