使用 char **,其中新元素覆盖以前的元素
Using char ** where new elements overwriting previous elements
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];
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用strcpy将char数组的元素复制到另一个数组
- 使用不带参数的函数访问结构元素
- 给定n个元素的m个集合.在C++中找到出现在最大集合数中的元素
- C++如何通过用户输入删除列表元素
- lower_bound()返回最后一个元素
- 基于多个条件处理地图中的所有元素
- 当将多个TypedArrayContents数组加载到V8数组中时(数组数组)时,最后一个元素将覆盖所有元素
- 覆盖数组元素时如何调用构造函数
- 在阵列中没有覆盖元素
- c ++ 我的 char* 数组被最后一个添加的元素覆盖
- 使用 char **,其中新元素覆盖以前的元素
- 尝试在文本文件中添加结构元素而不覆盖它
- 如何覆盖其他窗口应用程序的元素?
- 在 stl 映射中插入新项目时,将覆盖到第一个元素
- vector元素被覆盖
- 映射写入失败:无法覆盖第一个元素
- 字符串拆分为矢量<字符*>覆盖矢量元素
- 一旦满足指定容量,覆盖优先级队列末尾的元素