 |
C++Talk.NET C++ language newsgroups
|
| View previous topic :: View next topic |
| Author |
Message |
Chandra Shekhar Kumar Guest
|
Posted: Tue Jun 24, 2003 1:39 am Post subject: Re: C bug involving char arrays |
|
|
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
|
Posted: Tue Jun 24, 2003 1:33 pm Post subject: Re: C bug involving char arrays |
|
|
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.
HTH
Rob.
--
http://www.victim-prime.dsl.pipex.com/
|
|
| Back to top |
|
 |
Powered by phpBB © 2001, 2006 phpBB Group
|