Thread: vector<vector<const char*>> behaving strangely

  1. #1
    Registered User
    Join Date
    Jul 2013
    Posts
    6

    vector<vector<const char*>> behaving strangely

    Code:
    #include <iostream>
    #include <string>
    #include <vector>
    using namespace std;
    
    int main (int argc,char** argv){
        vector<vector<const char*>> b(3,vector<const char*>(3));
        for(int i=0;i<3;i++){
            for(int j=0;j<3;j++){
                b[i][j]=to_string(i*3+j).c_str();
            }
        }
        
        for(int i=0;i<3;i++){
            cout<<endl;
            for(int j=0;j<3;j++)cout<<b[i][j];
        }
        cout<<endl;
    }
    it return
    Code:
    888
    888
    888
    whereas it should return
    Code:
    012
    345
    678
    ps:i used -std=c++11;any help appreciated

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    What does the function to_string do?

  3. #3
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    I suppose to_string create the temp var of type std::string, so you are storing pointer to internal buffer of temp var which is destructed as soon as current statement is finished...

    You are happy to get any output at all instead of crash, when you are accessing freed memory.
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  4. #4
    Registered User
    Join Date
    Jul 2013
    Posts
    6
    std::to_string - cppreference.com just convert int to string

  5. #5
    Registered User
    Join Date
    Jul 2013
    Posts
    6
    thanks for info.are thare anyone who has an idea to overcome it

  6. #6
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    just store the std::string in your vector
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  7. #7
    Registered User
    Join Date
    Jul 2013
    Posts
    6
    ok.thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Copying string vector to char vector
    By Ducky in forum C++ Programming
    Replies: 21
    Last Post: 07-10-2013, 11:22 AM
  2. Replies: 1
    Last Post: 04-03-2009, 08:52 AM
  3. fprintf behaving strangely
    By cwmccart in forum C++ Programming
    Replies: 6
    Last Post: 07-17-2008, 09:56 AM
  4. Replies: 9
    Last Post: 04-04-2008, 12:41 PM
  5. connect vector<int> and vector<char>
    By hdragon in forum C++ Programming
    Replies: 1
    Last Post: 04-27-2006, 01:16 PM

Tags for this Thread