| strings/string-copy-1.c - Hele programmet. | Lektion 10 - slide 39 : 51 Program 1 |
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/* Copy s to a fresh allocated string and return it */
char *string_copy(const char *s){
char *new_str;
new_str = (char *)malloc(strlen(s)+1);
if (new_str == NULL){
printf("Cannot copy string.\n");
exit(EXIT_FAILURE);
}
strcpy(new_str,s);
return new_str;
}
int main(void) {
char s[] = "Aalborg University", *t;
t = string_copy(s);
strcpy(s,"---"); /* destroy s */
printf("The destroyed original is: %s.\nThe copy is: %s\n", s, t);
free(t);
return 0;
}