Newbie question about strings
Hi!
I''m trying to code a simple parser, but I don''t cope with
the strings c uses.
Just for fun, I tried to code a simple routine which copies
one string to another (I know that there is a predefined
function, but I want to try it myself in order to learn), but
it doesn''t work.
So this routine should look like this:
void CopyString(char *source, int length, char *dest)
{
}
Could anyone please tell me how I need to continue or finish this little routine, because I really don''t get it working. Do I have to allocate length bytes of memory for dest? And how, with ''new''? Ahgrr... that''s all much easier in Delphi,...but C
rules the world...so I need to learn it :-)
Thanks
LaBasX2
Here,
First of all there are other ways to doing this, but as you have already started off with this approach, let's build on this.
I assume, you have allocated memory for len no. of character bytes in your dest.
if you haven't ,do the malloc in main.
Let us know if you run into problems.
Neo
Edited by - NeoGL on August 22, 2000 7:12:20 PM
First of all there are other ways to doing this, but as you have already started off with this approach, let's build on this.
I assume, you have allocated memory for len no. of character bytes in your dest.
if you haven't ,do the malloc in main.
dest = (char *)malloc(len*sizeof(char));void CopyString(char *src, char *dest, int len){ int i; for(i=0;i<len;i++) *(dest + i) = *(src + i); *dest = NULL;}But, you don't really need the length, here's another way of doing it.void CopyString(char *src, char *dest){ int i; while(*src != NULL) *dest++ = *src++; *dest = NULL;}
Let us know if you run into problems.
Neo
Edited by - NeoGL on August 22, 2000 7:12:20 PM
Hi!
Thanks for your reply! Especially your second version is very
interesting for me as a newbie. It took me some time to figure out how it works but I think I even understand it now! :-)
Thanks again for your help!
cu
LaBasX2
Thanks for your reply! Especially your second version is very
interesting for me as a newbie. It took me some time to figure out how it works but I think I even understand it now! :-)
Thanks again for your help!
cu
LaBasX2
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement