tableaux dynamiques de char *
Bonjour,
J'avais fait un autre post, mais avec le mauvais titre, j'ouvre donc un nouveau topic. Pour une meilleure recherche parmi les topic
j'aimerai faire un tableaux dynamique de char *
j'ai ce code pour l'instant
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
int i = 0;
char **tab;
char *element = "ici";
char *test2;
int taille = 4;
char test01[7]="lool01\0";
char test02[7]="lool02\0";
char test03[7]="lool03\0";
char test04[7]="lool04\0";
tab = (char **) malloc(taille * sizeof(char *));
for(i=0;i<taille;i++)
{
*(tab+i)=test01;
if(i==2)
*(tab+i)=test02;
}
// allocation de 20 cases en plus
// for(i=0;i<20;i++)
// {
// tab = (char **) realloc(tab,(taille+i+1) * sizeof(char *));
// *(tab+i)=test04;
// }
tab = (char **) realloc(tab,(taille+i) * sizeof(char *));
*(tab+i)=test04;
for(i=0;i<taille+1;i++)
{
printf("%d - %s\n",i,*(tab+i));
}
free(tab);
} |
il fonctionne très bien voici la sortie :
0 - lool01
1 - lool01
2 - lool02
3 - lool01
4 - lool04
mais si on dé-commente la boucle for comme ici
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
int i = 0;
char **tab;
char *element = "ici";
char *test2;
int taille = 4;
char test01[7]="lool01\0";
char test02[7]="lool02\0";
char test03[7]="lool03\0";
char test04[7]="lool04\0";
tab = (char **) malloc(taille * sizeof(char *));
for(i=0;i<taille;i++)
{
*(tab+i)=test01;
if(i==2)
*(tab+i)=test02;
}
// allocation de 20 cases en plus
for(i=0;i<20;i++)
{
tab = (char **) realloc(tab,(taille+i+1) * sizeof(char *));
*(tab+i)=test04;
}
// tab = (char **) realloc(tab,(taille+i) * sizeof(char *));
// *(tab+i)=test04;
for(i=0;i<taille+16;i++)
{
printf("%d - %s\n",i,*(tab+i));
}
free(tab);
} |
La sortie n'est plus correcte
0 - lool04
1 - lool04
2 - lool04
3 - lool04
4 - lool04
5 - lool04
6 - lool04
7 - lool04
8 - lool04
9 - lool04
10 - lool04
11 - lool04
12 - lool04
13 - lool04
14 - lool04
15 - lool04
16 - lool04
17 - lool04
18 - lool04
19 - lool04
alors qu'au début on devrai avoir cela :
0 - lool01
1 - lool01
2 - lool02
3 - lool01
4 - lool04
....
Ce n'est pas le cas
De plus, le tableau ne comporte que 20 cases au lieu de 24.
(Si j'affiche jusqu'a 24 cases alors le prog fait un segmentation Erreur)
D'autre part j'utilise le même principe dans un projet plus conséquent et j'obtient cette erreur :
*** glibc detected *** ./my_pc: realloc(): invalid next size: 0x08aab710 ***
+Backtrace et memory map ...
Je pense fortement que mon realloc ne fonctionne pas.
Merci pour les réponses
CDLT