简体   繁体   中英

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. 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:

 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?

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.

As Neil Butterworth's answer suggest, the trouble is probably not with this code, but the place where you call it. 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. If you posted the method where you call this code it might be possible to see exactly what goes wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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