ASR3/ASR3.1/TP05 Pointeurs Signaux/exo0.c
2021-11-15 17:44:02 +01:00

59 lines
1.2 KiB
C

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
/*La fonction map permet de parcourir le tableau. */
void map(void *base,size_t n ,size_t size_elem,void(*f)(void *)){
int i;
char *ptr = (char*)base;
for(i=0;i<n;i++)
f((void*)(ptr+i*size_elem));
}
void print_int (void * i) {
printf("%d\n", *(int *)i ); // On force à le mettre en int
}
int cmp_int (const void* first, const void* second ) {
int firstInt = *(const int*)first;
int secondInt = *(const int*)second;
return firstInt - secondInt;
}
void print_string (void * s) {
printf ("%s", *(char* *)s ); // char* * => un pointeur sur un tableau de caractère
}
int cmp_string (const void* a, const void* b) {
const char* *ia = (const char* *)a;
const char* *ib = (const char* *)b;
return strcmp(*ia, *ib);
}
int main(){
int t1[10]={12,-7,1,-16,3,19,7,1,5,0};
char * t2[]={"chou","joujou","bijou","genou",
"caillou","hibou","pou"};
map(t1,10,sizeof(int),print_int);
printf("\n");
map(t2,7,sizeof(char*),print_string);
printf("\n");
qsort(t1,10,sizeof(int),cmp_int);
map(t1,10,sizeof(int),print_int);
printf("\n");
qsort(t2,7,sizeof(char *),cmp_string);
map(t2,7,sizeof(char*),print_string);
printf("\n");
}