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. :rolleyes:
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! :p