Skip to content
GitLab
Explore
Sign in
Primary navigation
Search or go to…
Project
C
cours
Manage
Activity
Members
Labels
Plan
Issues
Issue boards
Milestones
Wiki
Code
Merge requests
Repository
Branches
Commits
Tags
Repository graph
Compare revisions
Snippets
Build
Pipelines
Jobs
Pipeline schedules
Artifacts
Deploy
Releases
Model registry
Operate
Environments
Monitor
Incidents
Analyze
Value stream analytics
Contributor analytics
CI/CD analytics
Repository analytics
Model experiments
Help
Help
Support
GitLab documentation
Compare GitLab plans
Community forum
Contribute to GitLab
Provide feedback
Keyboard shortcuts
?
Snippets
Groups
Projects
Show more breadcrumbs
programmation_sequentielle
cours
Commits
d323a5e6
Verified
Commit
d323a5e6
authored
1 year ago
by
orestis.malaspin
Browse files
Options
Downloads
Patches
Plain Diff
added genericity
parent
19dbc9fd
No related branches found
Branches containing commit
No related tags found
No related merge requests found
Pipeline
#30699
passed
1 year ago
Stage: test
Changes
1
Pipelines
1
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
slides/genericite.md
+180
-0
180 additions, 0 deletions
slides/genericite.md
with
180 additions
and
0 deletions
slides/genericite.md
0 → 100644
+
180
−
0
View file @
d323a5e6
---
title
:
"
La
généricité"
date
:
"
2024-03-25"
---
# Problématique
*
En C on doit écrire chaque algorithme/structures de données pour des types
précis (
`int`
,
`double`
,
`char`
, ...).
```
void int_sort(int size, int tab[size]); // tri d'entiers
void double_sort(int size, int tab[size]); // tri de double
void char_sort(int size, char tab[size]); // tri de char
```
*
Duplication du code pour chaque type possible et imaginable.
*
On aimerait un moyen pour pouvoir représenter "n'importe quel type" sans
réécrire tout le code.
# La généricité
## Une "solution": `void *`{.C}
*
En général, un pointeur connaît son
**adresse**
et le
**type**
des données sur lesquelles il pointe.
```
C
int *a = malloc(sizeof(*a));
int *b = malloc(sizeof(int));
```
*
Un
`void *`
{.C} le connaît
**que**
son adresse, au programmeur de pas faire n'importe quoi.
*
Vous avez déjà utilisé des fonctions utilisant des
`void *`
{.C}
```
C
void *malloc(size_t size);
void free(void *);
```
# Attention danger
*
Ne permet pas au compilateur de vérifier les types.
*
Les données pointées n'ayant pas de type, il faut déréférencer avec précaution:
```
C
int a = 2;
void *b = &a; //jusqu'ici tout va bien
double c = *b; // argl!
```
*
Une attention accrue est nécessaire.
# Cas particuier: on sait pas comment libérer la mémoire
## Exemple
```
C
struct tab {
int *t;
}
struct tab *tmp = malloc(sizeof(*tmp));
tmp->t = malloc(10 * sizeof(*(tmp->t)));
free(tmp); // memory leak of tmp->t...
```
. . .
## Solution
```
C
free(tmp->t);
free(tmp);
```
# Exemple simple
*
On souhaite échanger deux pointeurs
```C
int *a = malloc();
int *b = malloc();
swap(&a, &b);
```
*
Comment écrire
`swap()`
pour que le code ci-dessus marche pour n'importe quel
type?
. . .
```
C
void swap(void **a, void **b) {
void *tmp = *a;
*a = *b;
*b = tmp;
}
```
# Cas d'utilisation (1/4)
\f
ootnotesize
*
La somme d'un tableau de type arbitraire (facile non?)
```C
void sum(void *tab, int length, size_t size_elem, void *zero,
void (*add)(void *, void *)) {
for (int i = 0; i < length; ++i) {
void *rhs = (void *)((char *)tab + i * size_elem);
add(zero, rhs);
} // de combien on "saute" avec un void *?
}
```
*
Pour des entiers
```C
void int_add(void *lhs, void *rhs) {
*((int *)lhs) += *((int *)rhs); // cast d'entiers
}
int zero = 0;
int tab[] = {1, -2, 4, 5};
sum(tab, 4, sizeof(int), &zero, int_add);
printf("%d\n", zero);
```
# Cas d'utilisation (2/4)
## Que fait cette fonction?
\f
ootnotesize
```
C
void *foo(void *tab, int n_items, int s_items,
bool (*bar)(void *, void *)) {
if (n_items <= 0 || s_items <= 0 || NULL == tab) {
return NULL;
}
void *elem = tab;
for (int i = 1; i < n_items; ++i) {
// void pointer arithmetics is illegal in C
// (gcc is ok though)
void *tmp_elem = (void *)((char *)tab + i*s_items);
if (bar(elem, tmp_elem)) {
elem = tmp_elem;
}
}
return elem;
}
```
# Cas d'utilisation (3/4)
## Avec un tableau de `int`{.C}
```
C
bool cmp_int(void *a, void *b) {
return (*(int *)a < *(int *)b);
}
int main() {
int tab[] = {-1, 2, 10, 3, 8};
int *a = foo(tab, 5, sizeof(int), cmp_int);
printf("a = %d\n", *a);
}
```
# Cas d'utilisation (4/4)
## Avec un tableau de `double`{.C}
```
C
bool cmp_dbl(void *a, void *b) {
return (*(double *)a < *(double *)b);
}
int main() {
double tab[] = {-1.2, 2.1, 10.5, 3.6, 18.1};
double *a = foo(tab, 5, sizeof(double), cmp_dbl);
printf("a = %f\n", *a);
}
```
This diff is collapsed.
Click to expand it.
Preview
0%
Loading
Try again
or
attach a new file
.
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Save comment
Cancel
Please
register
or
sign in
to comment