2

There's an issue in my code with nested vectors of strings. It is not printing the strings.

void foo(vector<vector<char const *> > const & vcp){
   vector<vector<char const *> >::const_iterator i(vcp.begin());
   vector<vector<char const *> >::const_iterator e(vcp.end());

   for(; i != e; ++i){
      vector<char const *>::const_iterator ci(i->begin());
      vector<char const *>::const_iterator ce(i->end());
      for(; ci != ce; ++ci) 
         cout<<*ci<<endl; //Not printing
   } 
}

int main(){
  std::vector<vector<char const *> > vvcp(3);
  std::vector<char const *> vcp(3);
  vcp.push_back(string("abcd").c_str());
  vcp.push_back(string("efgh").c_str());
  vcp.push_back(string("ijkl").c_str());

  vvcp.push_back(vcp);
  vvcp.push_back(vcp);
  foo(vvcp);
  return EXIT_SUCCESS;
}
moinudin
  • 134,091
  • 45
  • 190
  • 216
badmaash
  • 4,775
  • 7
  • 46
  • 61

2 Answers2

6

This has nothing to do with the vectors.

You are creating temporary std::string objects, getting pointers to their underlying data, and trying to use those pointers after the strings no longer exist. That is not allowed.

(Also, feeding '*x' to std::cout, where 'x' is a char const*, would print only the first character of the C-string.)

Just store the strings in the vectors. That's how you're meant to use them. .c_str() really only exists so you can work with legacy C code.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
1

I confirm @Karl. Change your code in C style:

vcp.push_back("abcd");
vcp.push_back("efgh");
vcp.push_back("ijkl");
Raphael Bossek
  • 1,904
  • 14
  • 25