Advertisement

Newbie question about strings

Started by August 22, 2000 04:52 PM
2 comments, last by LaBasX2 24 years, 3 months ago
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.
            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
Advertisement
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
If you are really going for simple one, here it is

while(*dest++ = *source++);

amazing but simplest code for string copy, by Bjarne Creator of C++.

This topic is closed to new replies.

Advertisement