function to copy one string to another one

This is a discussion on function to copy one string to another one within the C Programming forums, part of the General Programming Boards category; Hello, all. I am working through problems in the book Sam's Teach Yourself C for Linux in 21 Days and ...

  1. #1
    Registered User
    Join Date
    Jan 2005
    Posts
    14

    function to copy one string to another one

    Hello, all.
    I am working through problems in the book Sam's Teach Yourself C for Linux in 21 Days and all of a sudden I have hit a brick wall.

    The exercise I am trying now is to write a function that will copy one string into another string. I am able to do this inside of main(), but the exercise is to do it in a function outside of main(). I am new, and believe that usually strcpy() is used to do this sort of thing, but am feeling defeated by this, and have been trying for three days.

    I have read the stickies and hope that my posting the entire (short) program is not too far out of bounds, since I am so new that there could be errors anywhere.

    This *should* be fairly straight forward. There was an example of such a thing online from O'Reilly's Practical C but, I couldn't get it to work outside of main.

    Code:
         1
         2
         3  /* desperate.c */
         4  /* this is a fresh start at trying to do exercise9_5 in the */
         5  /* 21 Days book. */
         6  /* Write a function that copies one array of characters */
         7  /* into another.  (Hint: Do this just as in the programs you */
         8  /* wrote on Day 8). */
         9
        10  #include<stdio.h>
        11
        12  char source[32] = "This is the source string.     ";
        13  char dest[32] =   "This is the destination string.";
        14                   /*12345678901234567890123456789012*/
        15                   /* there are 32 slots in each array */
        16  char *p_source = &source[0];
        17  char *p_dest = &dest[0];
        18
        19  void good_function(char *p_source, char *p_dest);
        20
        21  int main(void)
        22  {
        23          puts("The stings in thier origninal state: \n");
        24          puts(source);
        25          puts(dest);
        26
        27          puts("\nNow, we copy source into dest");
        28
        29          void good_function(char *p_source, char *p_dest);
        30
        31          puts("here they are after that is done: \n");
        32
        33          puts(source);
        34          puts(dest);
        35
        36          return 0;
        37  }
        38
        39  void good_function(char *p_source, char *p_dest)
        40  {
        41          while (1)
        42          {
        43                  *p_dest = *p_source;
        44
        45                  /* exit if we copied the end of the string */
        46                  if (*p_dest == '\0')
        47                          break;
        48
        49                  ++p_dest;
        50                  ++p_dest;
        51          }
        52  }
        53
    Note: This compiles without errors on my machine, so at least I have THAT going in my direction!

  2. #2
    UT2004 Addict Kleid-0's Avatar
    Join Date
    Dec 2004
    Posts
    656
    Welcome newcomer! Next time you post, be sure to exclude the line numbers, they're hard to copy/paste/edit out

    Code:
    1
         2
         3  /* desperate.c */
         4  /* this is a fresh start at trying to do exercise9_5 in the */
         5  /* 21 Days book. */
         6  /* Write a function that copies one array of characters */
         7  /* into another.  (Hint: Do this just as in the programs you */
         8  /* wrote on Day 8). */
         9
        10  #include<stdio.h>
        11
        12  char source[32] = "This is the source string.     ";
        13  char dest[32] =   "This is the destination string.";
        14                   /*12345678901234567890123456789012*/
        15                   /* there are 32 slots in each array */
        16  char *p_source = &source[0];
        17  char *p_dest = &dest[0];
        18
        19  void good_function(char *p_source, char *p_dest);
        20
        21  int main(void)
        22  {
        23          puts("The stings in thier origninal state: \n");
        24          puts(source);
        25          puts(dest);
        26
        27          puts("\nNow, we copy source into dest");
        28
        29          // void good_function(char *p_source, char *p_dest);
                      good_function(source, dest);
        30
        31          puts("here they are after that is done: \n");
        32
        33          puts(source);
        34          puts(dest);
        35
        36          return 0;
        37  }
        38
        39  void good_function(char *p_source, char *p_dest)
        40  {
        41          while (1)
        42          {
        43                  *p_dest = *p_source;
        44
        45                  /* exit if we copied the end of the string */
        46                  if (*p_dest == '\0')
        47                          break;
        48
        49                  ++p_dest;
        50                  ++p_dest;
        51          }
        52  }
        53

  3. #3
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,638
    >> Note: This compiles without errors on my machine

    jesus, what compiler are you using?

    re-read the section of your book that covers functions calls.

    >> void good_function(char *p_source, char *p_dest);

    that should be:

    Code:
    good_function(p_source, p_dest);
    you don't have to form pointers to the arrays either - you could pass them to the function as is.

    [edit]
    too damn slow
    [/edit]
    Code:
    if( numeric_limits< byte >::digits != bits_per_byte )
        error( "program requires bits_per_byte-bit bytes" );
    24bbs.cpp

  4. #4
    UT2004 Addict Kleid-0's Avatar
    Join Date
    Dec 2004
    Posts
    656
    Quote Originally Posted by Sebastiani
    [edit]
    too damn slow
    [/edit]
    rofl! you were right though, I was wrong

    I sent the array instead of the pointer to the array, and I believe the pointer is correct. I would check it out, but I'm too lazy to remove the line numbers

  5. #5
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,638
    >> I sent the array instead of the pointer to the array, and I believe the pointer is correct.

    both are pointers to the data - either will work fine.
    Code:
    if( numeric_limits< byte >::digits != bits_per_byte )
        error( "program requires bits_per_byte-bit bytes" );
    24bbs.cpp

  6. #6
    Registered User
    Join Date
    Jan 2005
    Posts
    14
    Thank you all very much, I am off to try this out now.

    to Kleid-O:
    No more line numbers for me, thank you for the heads-up.
    When I call the function as:
    good_function(char *p_source, char *p_dest);


    to Sebastiani and Kleid-O:
    I get a warning from the compiler. (I'm using gcc)
    gcc version 3.3.4 (Debian 1:3.3.4-9ubuntu5).

    This is the warning:
    robstr12@speeder:~/C_Programming $ gcc -o desperate desperate.c -Wall
    desperate.c: In function `main':
    desperate.c:29: error: parse error before "char"

    to Sebastiani:
    Regarding passing the pointers to the function instead of the name,
    I think this author was trying to use this for demonstration purposes,
    In that this book is for people like me who are scrambling to learn
    the very fundamentals. That being said, I am under the impression
    that while that function call is not the best way to do it, that it
    should work, nonetheless, though unnecessarily complicated?

    Yes! You wrote: "both are pointers to the data - either will work fine."
    Thank you for clearing that up! And, along with my apologies for the
    line numbers, as I'm off to experiment with this, here is the code again,
    this time sans numbers (in case anyone else wants to mess with this).
    I'm still perplexed about the above error regarding
    error: parse error before "char"


    But, I will *NOT* give up on this! NO!



    Code:
    /* desperate.c */
    /* this is a fresh start at trying to do exercise9_5 in the */
    /* 21 Days book. */
    /* Write a function that copies one array of characters */
    /* into another.  (Hint: Do this just as in the programs you */
    /* wrote on Day 8). */
    
    #include<stdio.h>
    
    char source[32] = "This is the source string.     ";
    char dest[32] =   "This is the destination string.";
                     /*12345678901234567890123456789012*/
                     /* there are 32 slots in each array */
    char *p_source = &source[0];
    char *p_dest = &dest[0];
    
    void good_function(char *p_source, char *p_dest);
    
    int main(void)
    {
            puts("The stings in thier origninal state: \n");
            puts(source);
            puts(dest);
    
            puts("\nNow, we copy source into dest");
    
            good_function(char *p_source, char *p_dest);
    
            puts("here they are after that is done: \n");
    
            puts(source);
            puts(dest);
    
            return 0;
    }
    
    void good_function(char *p_source, char *p_dest)
    {
            while (1)
            {
                    *p_dest = *p_source;
    
                    /* exit if we copied the end of the string */
                    if (*p_dest == '\0')
                            break;
    
                    ++p_dest;
                    ++p_dest;
            }
    }

  7. #7
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,638
    look at my original post. that's how you call the function.
    Code:
    if( numeric_limits< byte >::digits != bits_per_byte )
        error( "program requires bits_per_byte-bit bytes" );
    24bbs.cpp

  8. #8
    Registered User
    Join Date
    Jan 2005
    Posts
    14
    Well, thank you so much, because now I have a working example of how it is possible to do this. (I don't care right now if its the best way, only if it will work at all).

    Here is what I have for it now, thanks to you guys. Interestingly, if I try to not use the keyword void in front of the call to the function, the gcc compiler complains. Maybe it is something particular to that compiler, AFAIK.
    Thank you again!

    Code:
    /* desperate.c */
    /* this is a fresh start at trying to do exercise9_5 in the */
    /* 21 Days book. */
    /* Write a function that copies one array of characters */
    /* into another.  (Hint: Do this just as in the programs you */
    /* wrote on Day 8). */
    
    #include<stdio.h>
    
    char source[32] = "This is the source string.     ";
    char dest[32] =   "This is the destination string.";
                     /*12345678901234567890123456789012*/
                     /* there are 32 slots in each array */
    char *p_source = &source[0];
    char *p_dest = &dest[0];
    
    void good_function(char *p_source, char *p_dest);
    
    int main(void)
    {
            puts("The stings in thier origninal state: \n");
            puts(source);
            puts(dest);
    
            puts("\nNow, we copy source into dest");
    
            void good_function(char *p_source, char *p_dest);
    
            puts("here they are after that is done: \n");
    
            puts(source);
            puts(dest);
    
            return 0;
    }
    
    void good_function(char *p_source, char *p_dest)
    {
            while (1)
            {
                    *p_dest = *p_source;
    
                    /* exit if we copied the end of the string */
                    if (*p_dest == '\0')
                            break;
    
                    ++p_dest;
                    ++p_dest;
            }
    }

  9. #9
    Registered User
    Join Date
    Jan 2005
    Posts
    14
    Quote Originally Posted by Sebastiani
    look at my original post. that's how you call the function.
    I must be missing something. This just can't possibly be this difficult.

    When I call the function as
    Code:
    good_function(p_source, p_dest);
    it compiles fine, but the output is this:

    The stings in thier origninal state:

    This is the source string.
    This is the destination string.

    Now, we copy source into dest
    Segmentation fault


    Since I'm such a n00b, please let me post the whole business with this call in the main()?

    Code:
    /* desperate.c */
    /* this is a fresh start at trying to do exercise9_5 in the */
    /* 21 Days book. */
    /* Write a function that copies one array of characters */
    /* into another.  (Hint: Do this just as in the programs you */
    /* wrote on Day 8). */
    
    #include<stdio.h>
    
    char source[32] = "This is the source string.     ";
    char dest[32] =   "This is the destination string.";
                     /*12345678901234567890123456789012*/
                     /* there are 32 slots in each array */
    char *p_source = &source[0];
    char *p_dest = &dest[0];
    
    void good_function(char *p_source, char *p_dest);
    
    int main(void)
    {
            puts("The stings in thier origninal state: \n");
            puts(source);
            puts(dest);
    
            puts("\nNow, we copy source into dest");
    
            /*
            void good_function(char *p_source, char *p_dest);
            */
    
            good_function(p_source, p_dest);
    
            puts("here they are after that is done: \n");
    
            puts(source);
            puts(dest);
    
            return 0;
    }
    
    void good_function(char *p_source, char *p_dest)
    {
            while (1)
            {
                    *p_dest = *p_source;
    
                    /* exit if we copied the end of the string */
                    if (*p_dest == '\0')
                            break;
    
                    ++p_dest;
                    ++p_dest;
            }
    }

  10. #10
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Instead of using a while(1) you could instead be using the source string as the loop control. Using a do-while, you could have it terminate when it reaches the end of the source string, after having copied the null over. I'll leave that rewrite as an exercise to the reader.

    Quzah.
    Hope is the first step on the road to disappointment.

  11. #11
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,638
    >> Now, we copy source into dest...Segmentation fault

    in your function's while loop, you increment the same pointer twice.
    Code:
    if( numeric_limits< byte >::digits != bits_per_byte )
        error( "program requires bits_per_byte-bit bytes" );
    24bbs.cpp

  12. #12
    Registered User
    Join Date
    Jan 2005
    Posts
    14
    Quote Originally Posted by Sebastiani
    >> Now, we copy source into dest...Segmentation fault

    in your function's while loop, you increment the same pointer twice.
    Doh!
    A gross oversite! Yes, it works famously now!
    Thank you all so much! It was something, hitting that wall the last three days. Up till then, it was going much smoother. But, its all good.

    To Quzah:
    Yes, I am going to work through this book first, to get a rough overview, and
    then, on the next go 'round, I will work through the O'Reilly book, Practical C , and by then I will be accustomed to at least the basic ideas, so that I can do things in a more efficient way, or what have you. As for now, I'm still struggling to get the stuff to work.

    Once again, thank you for helping me over the hurdle.

  13. #13
    ... kermit's Avatar
    Join Date
    Jan 2003
    Posts
    1,528
    Practical C quite often does not get good reviews, so keep that in mind when you go though it. You can take a look here. You could also search this forum for that title - I am sure some comments have been made about it. Incidentally, ACCU has a fairly decent book review section to look over. It is a helpful reference when you are trying to decide on a book to buy. Your Sams book is not bad, though there are some inaccuracies in it as well. Lurk on this board and you will learn about the things you should and should not do when writing a C program.

    ~/

  14. #14
    Registered User
    Join Date
    Jan 2005
    Posts
    14
    Quote Originally Posted by kermit
    Practical C quite often does not get good reviews, so keep that in mind when you go though it. You can take a look here. You could also search this forum for that title - I am sure some comments have been made about it. Incidentally, ACCU has a fairly decent book review section to look over. It is a helpful reference when you are trying to decide on a book to buy. Your Sams book is not bad, though there are some inaccuracies in it as well. Lurk on this board and you will learn about the things you should and should not do when writing a C program.

    ~/
    Thank you, kermit.
    I already have the Practical C, and am now SURE that reading over these posts here will be a must-do for me!

  15. #15
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Not a great habit (global variables and function parameters having the same name):
    Code:
    char *p_source = &source[0];
    char *p_dest = &dest[0];
    
    int main(void)
    {
       /* ... */
       good_function(p_source, p_dest);
       /* ... */
       return 0;
    }
    
    void good_function(char *p_source, char *p_dest)
    {
       /* ... */
    }
    Which is who in the function good_function? Here it may not make much of a difference, but such habits may bite you later.
    Last edited by Dave_Sinkula; 01-28-2005 at 10:11 PM.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 03-03-2006, 01:11 AM
  2. string copy function
    By rahulsk1947 in forum C Programming
    Replies: 8
    Last Post: 02-14-2006, 06:13 PM
  3. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  4. Program using classes - keeps crashing
    By webren in forum C++ Programming
    Replies: 4
    Last Post: 09-16-2005, 03:58 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21