为什么我得到这个字符指针的不同结果?

Why do I get different results for this cout of pointer of char?

本文关键字:结果 指针 字符 为什么      更新时间:2023-10-16

我写同样的东西得到两个不同的结果,但在不同的函数中。

我正在尝试创建一个字符数组,一个字母一个字母,然后我把它放在一个字符**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**)以希望之后使用该指针是错误的