Mail Archives: djgpp/1998/03/25/10:15:45
In article <Ip5nMWq00WB815Vks0 AT andrew DOT cmu DOT edu>, James W Sager Iii
<sager+@andrew.cmu.edu> writes
>appearantly, if you go past the terminating character on char*'s
>you pass to functions, they accept whatever is past the one character
>as the input for the function the next time.
>Hense
>'_' is the first character
>'PCX' is the next three.
No, before you call your function the an area of memory looks like this
'1' '\0' '2' '\0' ... (other memory locations potentially your code)
^ ^
"1" "2"
after your strcat it looks like
'1' '_' 'P' 'C' 'X' '\0'
^ ^ ^
"1" "2" memory you shouldn't have messed with
(these diagrams are supposed to show the memory pointed to by the
arguments to your function call)
This is not a problem with function call, but your misunderstanding of
'strings' i.e. they don't really exist in C the same way ints do. You
are writting to memory with no idea of what is in it or will be in it in
the future.
>I guess to manipulate strings one should first copy them to a new string.
>Which is:
Almost.
>void wierd(char *s1)
>{
>char *s2;
// Allocate enough memory for the two strings and a '\0' string
// terminator
s2 = new char[strlen(s1) + strlen("_PCX") + 1];
>strcpy(s2,s1);
>strcat(s2,"_PCX");
>cout<<s2<<endl;
// free up the memory we allocated earlier
delete [] s2;
>}
Apart from any typos this should solve the problems you are going to
have with your revised function.
--
James Undery <james AT ghoti DOT demon DOT co DOT uk>
- Raw text -