From 2a56c743a2ebde2667a9f91c135c3c2c044a228e Mon Sep 17 00:00:00 2001 From: "paul.albuquer" <paul.albuquerque@hesge.ch> Date: Mon, 18 Oct 2021 15:33:11 +0200 Subject: [PATCH] added folder for pointer exercises, deep-shallow copy --- .../pointeurs/string_deep_shallow_copy.c | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 source_codes/pointeurs/string_deep_shallow_copy.c diff --git a/source_codes/pointeurs/string_deep_shallow_copy.c b/source_codes/pointeurs/string_deep_shallow_copy.c new file mode 100644 index 0000000..588cb71 --- /dev/null +++ b/source_codes/pointeurs/string_deep_shallow_copy.c @@ -0,0 +1,72 @@ +#include <stdio.h> +#include <stdlib.h> + +typedef struct _chaine { + char* str; + int len; +} chaine; + +int length(char* phrase) { + if (NULL == phrase) return -1;; + int len = 0; + while (0 != phrase[len]) { + len++; + } + return len; +} + +chaine chaine_build(char* phrase) { + chaine ch; + ch.len = length(phrase); + ch.str = malloc((ch.len+1)*sizeof(char)); + for (int i=0;i<ch.len;i++) { + ch.str[i] = phrase[i]; + } + return ch; +} + +chaine deep_copy(chaine ch) { + return chaine_build(ch.str); +} + +// Dangereux, car plusieurs pointeurs sur le même tableau de caractères !!! +// A éviter !!! +chaine shallow_copy(chaine ch) { + chaine cpy; + cpy.len = ch.len; + cpy.str = ch.str; + return cpy; +} + +// S'il y a plusieurs pointeurs sur le même tableau de caractères, +// les autres pointeurs ne seront pas mis à NULL +void chaine_free(chaine* ch) { + if (NULL != ch->str) + free(ch->str); + ch->str = NULL; + } + ch->len = -1; +} + +void main() { + char* tutu = malloc(10*sizeof(char)); + for (int i=0;i<6;i++) tutu[i] = 'b'; + tutu[6] = 0; + chaine ch = chaine_build(tutu); + chaine tmp = deep_copy(ch); + ch.str[0] = 'a'; + printf("%d\n",ch.len); + printf("%s\n",ch.str); + printf("%d\n",tmp.len); + printf("%s\n",tmp.str); +} + + + + + + + + + + -- GitLab