J'ai des problèmes avec ce programme. L'idée est de lire des chaînes à partir d'un fichier texte et de les inclure dans un tableau dynamique 2D avec un nombre constant de colonnes et un nombre variable de lignes. Si le nombre initial de lignes n'est pas suffisant pour inclure toutes les chaînes, le bloc de mémoire du tableau doit être réaffecté. Le code compile bien mais l'exécution est impossible.Réallocation de tableau dynamique 2D
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#define SIZE 80
#define DELTA 5
char** include(char b[SIZE],char** p,int n,int k,int flag);
void output(char **p,int k);
int main(void)
{
char **ptr;
FILE *fp;
int i=0,koef=1;
char buffer[SIZE];
if((ptr=(char **)malloc(DELTA*sizeof(char *)))==NULL){
printf("Error!Memory not allocated!\n");
exit(1);
}
if((fp=fopen("test.txt", "r")) == NULL) {
printf("Cannot open file.\n");
exit(1);
}
do{
if(fgets(buffer,sizeof(buffer),fp)==NULL){
printf("Error while reding file!\n");
exit(1);
}
if(i<(DELTA*koef))
ptr=include(buffer,ptr,i,koef,1);
else {
koef++;
ptr=include(buffer,ptr,i,koef,2);
}
i++;
}while(!feof(fp));
free(ptr);
return 0;
}
char** include(char b[SIZE],char** p,int n,int k,int flag)
{
switch(flag){
case 1: *(p+n)=(char *)malloc(sizeof(b));
strcpy(*(p+n),b);
break;
case 2: if((p=(char **)realloc(p,k*DELTA*sizeof(char *)))==NULL){
printf("Error!Memory not allocated!\n");
exit(1);
}
*(p+n)=(char *)malloc(sizeof(b));
strcpy(*(p+n),b);
break;
}
return p;
}
void output(char **p,int k)
{
int j;
for(j=0;j<k;j++)
printf("%s\n",*(p+j));
}
Est-ce ce devoir? – batbrat