Re: C bug involving char arrays

Discussion in 'C++' started by Rob Williscroft, Jun 24, 2003.

  1. David Baldwin wrote in
    news:p:

    > Ok I believe this falls under the category of stupid newbie question
    > ;p
    >
    > The function below returns values correctly whenever length is > 3.
    > However, anything from 1-3 returns an array of correct values followed
    > by garbage.
    >
    > Any insight on what I'm doing wrong here?
    >
    > Thanks
    >
    > char* getBlock(char* array, int length, int start){
    > if(length == 0) return "";
    >
    > char* c = new char[length];


    You need space for the terminating null char '\0'.

    char* c = new char[length + 1];

    > for(int z=0;z<length;z++){
    > c[z] = array[z+start];
    > }


    terminate the array:

    c[length] = '\0'; // = 0 will also do.

    > return c;
    > }
    >


    HTH

    Rob.
    --
    http://www.victim-prime.dsl.pipex.com/
    Rob Williscroft, Jun 24, 2003
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Chandra Shekhar Kumar

    Re: C bug involving char arrays

    Chandra Shekhar Kumar, Jun 24, 2003, in forum: C++
    Replies:
    0
    Views:
    972
    Chandra Shekhar Kumar
    Jun 24, 2003
  2. lovecreatesbeauty
    Replies:
    1
    Views:
    1,034
    Ian Collins
    May 9, 2006
  3. Lucas Nussbaum
    Replies:
    2
    Views:
    148
    Lucas Nussbaum
    Jan 4, 2005
  4. Joel VanderWerf

    bug involving condition variables

    Joel VanderWerf, Jul 14, 2008, in forum: Ruby
    Replies:
    3
    Views:
    85
    Joel VanderWerf
    Jul 14, 2008
  5. Ken Ballou
    Replies:
    0
    Views:
    77
    Ken Ballou
    May 14, 2009
Loading...

Share This Page