为什么我得到这个字符指针的不同结果?
Why do I get different results for this cout of pointer of char?
我写同样的东西得到两个不同的结果,但在不同的函数中。
我正在尝试创建一个字符数组,一个字母一个字母,然后我把它放在一个字符**v中。如您所见,我在 create_vect() 和 main() 函数中有 cout v[i],如果我运行代码,每次都会得到不同的结果。我很困惑。为什么会这样,我该怎么做才能对其进行故障排除,以便我第二次也得到"000"作为结果,正如我所追求的那样?
#include <string.h>
#include <math.h>
using namespace std;
void create_vect( char **&v){
v=new char*[3];
for (int i=0;i<3;i++){
char wordd[4];
wordd[0]='0';
wordd[1]='0';
wordd[2]='0';
wordd[3]=' ';
v[i]=wordd;
cout<<endl<<v[i]; //here I get the right thing
}
}
int main(){
char **v;
create_vect(v);
for (int i=0;i<3;i++){
cout<<endl<<v[i]; //here i get something weird ascii sign
}
}
编辑:我的错,我只是想把它翻译成英文,这样更容易看到我用我的代码想要什么,我错过了一个字。我非常感谢您的帮助,因为我需要做出哪些更改才能使其正常工作。我有点迷茫。谢谢你,再次为我的粗心大意的错误感到抱歉。
当您调用create_vect
并进入for
循环时,您将在堆栈上创建一个类型为char[4]
的变量wordd
。但它的生命周期只是for
循环的一次迭代。使用v[i]=wordd;
将wordd
的第一个元素的地址分配给v[i]
。数组衰减到指向第一个元素的指针。只要变量wordd
存在,就可以打印它。但是,当您尝试在生命周期结束后访问内存时,会出现未定义的行为。有时您的程序可以按预期工作,有时它会打印垃圾。
要解决问题,您可以在堆上使用动态内存分配,也可以使用 stl 容器,例如std::vector<std::string>
(它可能使用动态内存分配并按值复制)。请记住清理动态分配的内存。
此外,您不应该在 c++ 代码中使用 c 标头(math.h、string.h)。使用cmath,cstring。不要使用命名空间 std;。使用 std::cout, std::endl, ...
#include <cstring>
#include <cmath>
#include <iostream>
void create_vect(char **&v) {
v=new char*[3];
for (int i = 0; i < 3; ++i) {
v[i] = new char[4];
v[i][0]='0';
v[i][1]='0';
v[i][2]='0';
v[i][3]=' ';
std::cout << std::endl << v[i]; //here I get the right thing
}
}
int main(){
char **v;
create_vect(v);
for (int i = 0; i < 3; ++i) {
std::cout << std::endl << v[i]; //here i get something weird ascii sign
}
// Clean-up
for (int i = 0; i < 3; ++i) {
delete[] v[i];
}
delete[] v;
return 0;
}
我不太确定你想实现什么,但也许是这样的:
#include <string.h>
#include <math.h>
#include <iostream>
void create_vect(char *&v){
char wordd[] = {'0', '0', '0'};
v = new char[3];
for (int i=0; i<3; ++i){
v[i] = wordd[i];
std::cout << v[i] << std::endl;
}
}
int main(){
char *v;
std::cout << "inside the function" << std::endl;
create_vect(v);
std::cout << "outside the function" << std::endl;
for (int i=0;i<3;++i){
std::cout << v[i] << std::endl;
}
delete[] v;
return 0;
}
或者@ThomasSablik建议的,其中请注意:
当函数被返回(函数被调用并结束)时,函数内的所有本地对象都会被破坏,并且它们占用的内存被释放。
因此,在函数内创建一个对象(在本例中为char*
)并将其地址分配给非本地指针(在本例中为char**
)以希望之后使用该指针是错误的!
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 取消引用指向整数的指针时获得不同的结果
- 指针数组中的意外结果
- 使用指针访问数组元素时出现意外结果
- C++数组和指针的大小的结果
- C++ 函数指针的计算结果为 1
- 对象指针打印结果以相反的顺序进行
- 使用 OpenCV 原始指针和 lambda 作为直方图的不同结果
- 插入指针数组会删除上一个结果
- 打印整数指针元素时的结果不同
- 错误:通过指针显示重复的结果
- 当应该删除其目标时,为什么此智能指针给出正确的结果
- 为什么我得到这个字符指针的不同结果?
- 在我的C++链表实现中取消引用节点指针,给出意想不到的结果
- 我可以将C 17 Capture lambda ConstexPR转换操作符的结果用作函数指针模板非类型参数吗?
- Cout删除了(未签名的字符)指针,给了我意外的结果
- 为什么无法将 std::bind 的结果分配给函数指针
- 如何否定MEM_FN创建的功能指针的结果
- 返回指向操作+的结果的指针
- 为什么在同一类中使用不同的(共享_ptr和正常)指针构造函数,我会得到不同的结果