简体   繁体   English

C ++ push_back无法正常运行

[英]c++ push_back doesn't work as it is supposed

I have a class symbol_table that has a vector of objects of another class row_st.also I have an enter method where inserts objects of row_st with a passed name into the vector of desired symbol_table.but when I call the enter to enter objects with name : a;b;c;Iwill get the following result: a,b,c;b,c;c.the first element of vector gets the name of all the entered objects. 我有一个symbol_table类,它具有另一个类row_st的对象向量。也有一个enter方法,其中将具有传递名称的row_st对象插入所需的symbol_table的向量中,但是当我调用enter来输入具有name的对象时: a; b; c;我将得到以下结果:a,b,c; b,c; c.vector的第一个元素获取所有输入对象的名称。 and the second element also gets the name of the later entries. 第二个元素还获取后面条目的名称。

  class row_st
  {
   public:
      char* name;
      type_u type;//int:0,flaot:1;char:2,bool:3,array:
      int offset;
      symbol_table *next;
      symbol_table *current;
  };
  class symbol_table
  {
   public:
    vector <row_st *> row;
     int type;
     int header;
     int starting_stmt;
     int index;
     int i;
     symbol_table *previous;
     symbol_table(){ header=0;
      previous=0; index=0;i=0;starting_stmt=0;}
  };

and here it is the enter method: 这是enter方法:

 int enter(symbol_table *table,char* name,type_u type){
     row_st *t=new row_st;
t->name=name;
t->type=type;
t->offset=table->index;
t->current=table;
table->index++;
t->next=0;
table->row.push_back(t);
table->header +=1;
return table->row.size()-1;
   }

the push_backed elements all points to the same address.the new call makes the same row_st every time it is called.what should I do? push_backed元素都指向相同的地址。每次调用时,新调用都会产生相同的row_st。我该怎么办?

You can't use character pointers like that - you need to allocate storage to them. 您不能使用这样的字符指针-您需要为其分配存储空间。 But as you are using C++, you should remove them and replace them with instances of the std::string class, which will manage storage for you. 但是,当您使用C ++时,应删除它们,并用std :: string类的实例替换它们,该实例将为您管理存储。

As Neil Butterworth's answer suggest, the trouble is probably not with this code, but the place where you call it. 正如尼尔·巴特沃思(Neil Butterworth)的答案所暗示的那样,问题可能不在于此代码,而在于调用它的地方。 Using character pointers does not make it impossible to make things work, just harder. 使用字符指针不会使事情变得可行,只是变得更加困难。

The problem in this case is definitely not with push_back. 在这种情况下,问题绝对在于push_back。 If you posted the method where you call this code it might be possible to see exactly what goes wrong. 如果将方法发布到调用此代码的位置,则有可能确切地找出问题所在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM