Skip to content
Snippets Groups Projects
Commit 2a56c743 authored by paul.albuquer's avatar paul.albuquer
Browse files

added folder for pointer exercises, deep-shallow copy

parent 0ea6fbe2
No related branches found
No related tags found
No related merge requests found
Pipeline #14748 passed
#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);
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment