1 /* 2 * stringvar.c 3 * 4 * Beispiel-Anwendung von str-Funktionen 5 * 6 * Autor: H.Drachenfels 7 * Erstellt am: 25.2.2015 / 10.11.2017 (C11) 8 */
9
10 #include <stdio.h>
11 #include <stddef.h>
12 #include <stdlib.h>
13 #include <string.h> // strxxx functions
14
15 int main(void)
16 {
17 char a[] = "halli";
18 const char *s = "hallo";
19 char *t = NULL;
20
21 //---------------------------- compare, copy and concatenate strings
22 if (strcmp(a, s) < 0)
23 {
24 t = (char*) malloc(sizeof a + strlen(s));
25 if (t == NULL)
26 {
27 fprintf(stderr, "Kein Heap-Speicher mehr\n");
28 return 1;
29 }
30
31 strcat(strcpy(t, a), s); // or: strcpy(t, a); strcat(t, s);
32 }
33 else
34 {
35 t = (char*) calloc(1, sizeof (char));
36 if (t == NULL)
37 {
38 fprintf(stderr, "Kein Heap-Speicher mehr\n");
39 return 1;
40 }
41 }
42
43 //-------------------------------- print string values and addresses
44 printf("a = %p %s\ns = %p %s\nt = %p %s\n",
45 (void*) a, a, (void*) s, s, (void*) t, t);
46
47 printf("sizeof a = %zu\n", sizeof a);
48 printf("sizeof s = %zu\n", sizeof s);
49 printf("sizeof t = %zu\n", sizeof t);
50
51 printf("strlen(a) = %zu\n", strlen(a));
52 printf("strlen(s) = %zu\n", strlen(s));
53 printf("strlen(t) = %zu\n", strlen(t));
54
55 s = a; // copies the address, not the string
56 // a = s; syntax error
57
58 free(t);
59
60 return 0;
61 }
62