C++Talk.NET Forum Index C++Talk.NET
C++ language newsgroups
 
Archives   FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

Re: C bug involving char arrays

 
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ language (comp.lang.c++)
View previous topic :: View next topic  
Author Message
Chandra Shekhar Kumar
Guest





PostPosted: Tue Jun 24, 2003 1:39 am    Post subject: Re: C bug involving char arrays Reply with quote





David Baldwin wrote:

Quote:
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];
for(int z=0;z c[z] = array[z+start];
}
return c;
}

let me take the case when length = 5, start = 4;
then this loop
for(int z=0;z c[z] = array[z+start]; }

then the index in the array is from 4 to 8, but where u r insuring
this...means the array u r passing might not have that much size...


Back to top
Rob Williscroft
Guest





PostPosted: Tue Jun 24, 2003 1:33 pm    Post subject: Re: C bug involving char arrays Reply with quote



David Baldwin wrote in
news:Pine.GSO.4.53.0306240914070.1374 (AT) denali (DOT) ccs.neu.edu:

Quote:
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 ''.

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

Quote:
for(int z=0;z c[z] = array[z+start];
}

terminate the array:

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

Quote:
return c;
}


HTH

Rob.
--
http://www.victim-prime.dsl.pipex.com/

Back to top
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ language (comp.lang.c++) All times are GMT
Page 1 of 1

 
 


Powered by phpBB © 2001, 2006 phpBB Group