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

Thread: C++ Array Problem

  1. #1
    Join Date
    Jun 2008
    Posts
    2

    C++ Array Problem

    #include <iostream>
    using namespace std;
    int main()
    {
    char* test = new char[5];
    test[0] = 'h';
    test[1] = 'e';
    test[2] = 'l';
    test[3] = 'l';
    test[4] = 'o';
    cout << test << " : " << strlen(test) << " : " << _msize(test) << endl;
    int a;
    cin >> a;
    return 0;
    }

    Why is this outputting : hello : 24 : 5

    I could understand the first 5 characters being random chars since they hadn't been initialized, but why are there an extra 19 characters added onto this array? strlen(test) gives 24, while _msize(test) does tell me how big it's supposed to be.

  2. #2
    Join Date
    May 2008
    Posts
    96

    Re: C++ Array Problem

    You forgot to add a '\0' (nul) char at the end of your string.
    Code:
    ...
    char* test = new char[6];
    ...
    test[5] = '\0';
    cout << ...
    :-)

  3. #3
    Join Date
    Jun 2008
    Posts
    2

    Re: C++ Array Problem

    You are a genious. Thank you so much.

  4. #4
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: C++ Array Problem

    Quote Originally Posted by gambitsunob
    _msize(test) does tell me how big it's supposed to be.
    Don't rely on that.

Posting Permissions

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


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)