From 77bfb2ccd3152c1f41d43dc192ba86ca8fd0f72f Mon Sep 17 00:00:00 2001 From: Anhgelus Morhtuuzh Date: Fri, 21 Feb 2025 17:50:16 +0100 Subject: =?UTF-8?q?Ajout=20de=20la=20semaine=20des=20cours=20du=2014=20au?= =?UTF-8?q?=2021=20f=C3=A9vrier?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- semestre 2/informatique/td/4- arrays.md | 2 +- .../td/5- cha\303\256nes de caract\303\250re.md" | 41 ++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 "semestre 2/informatique/td/5- cha\303\256nes de caract\303\250re.md" (limited to 'semestre 2/informatique/td') diff --git a/semestre 2/informatique/td/4- arrays.md b/semestre 2/informatique/td/4- arrays.md index 5c1067d..12ffb49 100644 --- a/semestre 2/informatique/td/4- arrays.md +++ b/semestre 2/informatique/td/4- arrays.md @@ -7,4 +7,4 @@ semestre: 2 --- Pour utiliser du random en C, on a besoin de `stdlib.h` - `srand` permet de set la seed (on peut utiliser `time(NULL))` qui est dans `time.h` pour utiliser le timestamp actuel) -- `rand` donne un aléatoire entre 0 et `RAND_MAX` (une constante prédéfinie) \ No newline at end of file +- `rand` donne un aléatoire entre 0 et `RAND_MAX` (une constante prédéfinie) diff --git "a/semestre 2/informatique/td/5- cha\303\256nes de caract\303\250re.md" "b/semestre 2/informatique/td/5- cha\303\256nes de caract\303\250re.md" new file mode 100644 index 0000000..0587412 --- /dev/null +++ "b/semestre 2/informatique/td/5- cha\303\256nes de caract\303\250re.md" @@ -0,0 +1,41 @@ +--- +tags: + - sorbonne + - informatique + - td +semestre: 2 +--- +Déclarer un caractère : `char c = 'H';` +Déclarer string : +```c +char *c = "Hello"; +char c[] = "Hello"; +char c[6] = "Hello"; // car il y a \0 à la fin +char c[] = {'H', 'e', 'l', 'l', 'o', '\0'}; // si on ne finit par \0, on fait un array de caractères et non un string +``` + +> [!warning] Modification d'un string +> Quand on déclare une chaîne avec les `"`, on déclare une constante. Pour la modifier, on a besoin d'utiliser la déclaration en tableau (avec les `{}`) + +Toutes les chaînes de caractère finissent par `'\0'` + +On peut utiliser la lib `string.h` + +```c +int int_to_str(int val){ + int i = 1; + int tmp_val = val; + for (i = 1; tmp_val % 10 != tmp_val; i++) tmp_val /= 10; + char *str = malloc(sizeof(char) * (i+1)); // +1 car on n'oublie pas le '\0' + str[i] = '\0'; // on rajoute de suite le '\0' + for (int j = 0; j <= i; j++) { + int c = val % pow(10, j); + val -= c; + str[j] = c + 48; + } + return str; +} +``` + +On ne peut pas écrire `int arr[][];` ! +|> on doit forcément indiquer la taille des sous-tableaux, e.g. `int arr[][5];` -- cgit v1.2.3