CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 10 of 10

Thread: Help with char*

Threaded View

  1. #1
    Join Date
    Sep 2009
    Posts
    11

    Help with char*

    Please can some one help me point out what's wrong with the code below. There's an intermittent error when trying to push_back into the vector.

    I need to use char* because an API I'll be using will be expecting char*

    Code:
    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    int main()
    {
    
        char* s = "The quick brown fox jumps over the lazy dog The quick brown's fox jumps over's the lazy dog. The quick brown fox jumps over the lazy dog The quick brown fox jumps over the lazy dog";
        vector<char*> textarray;
    
        char* buffer;
        int firstpos = 0;
        int bsize = 0;
    
        for (int i = 0; i < strlen(s); i++)
        {
            if (s[i] == ' ')
            {
                bsize = i - firstpos + 1;
    
                if (bsize > 0)
                {
                    buffer = new char[bsize];
                    strncpy(buffer, &s[firstpos], bsize);
                    buffer[bsize] = NULL;
                    cout << "bsize: " << bsize << " " << strlen(buffer) << " (" << buffer << ")" << endl;
                    //delete [] buffer;
                    textarray.push_back(buffer);
                }
    
                firstpos = i + 1;
            }
        }
    
        for (int i=0; i < textarray.size(); i++)
        {
            cout << "deleted : " << textarray[i] << endl;
            delete [] textarray[i];
        }
    
        return 0;
    }
    ps. I'm using latest CodeBlocks with mingw
    Last edited by cic.lemur; September 25th, 2009 at 11:25 PM. Reason: added info

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured