Added partial tutorial 5-5. Function copies n chars from source to destination.
[C-Programming-Examples.git] / ex_5-5.c
blob146df832cd977c0c35b9dc683dac8974265b45f5
1 #include <string.h>
2 #include <stdio.h>
4 /* print contents of array */
5 void print_array(char s[])
7 int i;
8 for(i = 0; i < strlen(s); i++)
9 printf("%c", s[i]);
10 printf("\n");
15 Copy at most n chars of string source into string dest.
16 Pad with '\0' if source has fewer chars than dest.
19 char *ss_strncpy(char *dest, const char *source, int n)
21 char *d = dest;
22 if(n >= 0 || n == '\0')
24 while(--n >= 0 && (*dest++ = *source++) != '\0')
25 continue;
26 while(--n > 0)
27 *dest++ = '\0';
30 return d;
33 int main()
35 char source[] = { "Destination after..." };
36 char dest[] = { "This is the destination before..." };
38 print_array(dest);
40 char *ans;
42 ans = strncpy(dest, source, 20);
44 printf("%p\n", ans);
45 print_array(dest);
47 printf("\n\n");
49 char source2[] = { "Destination after..." };
50 char dest2[] = { "This is the destination before..." };
52 print_array(dest2);
54 ss_strncpy(dest2, source2, 20);
56 printf("%p\n", ans);
57 print_array(dest2);
58 return 1;