www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/03/25/10:15:45

From: James Undery <james AT ghoti DOT demon DOT co DOT uk>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: ?Functions recieving strings?
Date: Wed, 25 Mar 1998 14:24:42 +0000
Organization: None unless you want to pay me
Message-ID: <pERuGFAqORG1EwJO@ghoti.demon.co.uk>
References: <Ip5nMWq00WB815Vks0 AT andrew DOT cmu DOT edu>
Reply-To: james AT ghoti DOT demon DOT co DOT uk
NNTP-Posting-Host: ghoti.demon.co.uk
MIME-Version: 1.0
Lines: 54
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

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 -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019