[英]error using pointers in functions c++
#include <iostream>
using namespace std;
#include <string>
#include <map>
typedef struct node{
char a;
map<char , node*> b;
}node;
node a[26] ;
void add(string s){
node *prev = &(a[s[0]-'a']);
int i = 0;
int len = s.length();
for(i = 1; i < len; ++i){
map<char,node*>::iterator it = ((*prev).b).find(s[i]);
if(it != ((*prev).b).end()){
prev = it->second;
}
else{
cout << (*prev).a << endl;
node pt;
pt.a = s[i];
((*prev).b)[s[i]] = &pt;
prev = &pt;
}
}
}
int main(){
string s = "helloworld";
string t = "htllothis";
int i = 0 ;
for(i = 0;i < 26;++i){
a[i].a = 'a'+i;
}
add(s);
add(t);
return 0;
}
I am trying to implement tire datastructure using map and char but cout<< (*prev).a
is printing some other chars. 我正在尝试使用map和char实现轮胎数据结构,但是
cout<< (*prev).a
正在打印其他一些char。 What is the mistake I have done? 我犯了什么错误?
First of all (*prev).b
is equivalent to prev->b
, I do not understand why you use ->
for iterator but not for this pointer, it is difficult to read your code. 首先
(*prev).b
等同于prev->b
,我不明白您为什么使用->
进行迭代,但不使用此指针,因此很难读取您的代码。
Main problem that you insert pointer to a local object into map: 您将指向本地对象的指针插入地图的主要问题是:
cout << (*prev).a << endl;
node pt;
pt.a = s[i];
((*prev).b)[s[i]] = &pt;
prev = &pt;
After leaving this block that pointer becomes invalid and you get random errors. 离开此块后,该指针将变为无效,并且您将获得随机错误。 You either should create node by operator new and better have smart pointer in your map, or keep node by value.
您应该按新的运算符创建节点,最好在地图中具有智能指针,或者按值保留节点。
(...)
node pt;
pt.a = s[i];
((*prev).b)[s[i]] = &pt;
prev = &pt;
(...)
In your add
function you're creating a local node
and passing its address into an entry of the map and then make it the prev
node. 在你的
add
功能,你要创建一个本地node
,并通过其地址到地图的入口,然后使它的prev
节点。 Once the variable is out of scope it is deleted and your prev
node points to an invalid address. 一旦变量超出范围就被删除,你的
prev
节点指向的地址无效。 So next time you print prev
anything could happen as it is Undefined Behaviour. 因此,下次打印
prev
可能会发生任何事情,因为这是未定义的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.