Hi! I have problems with this program. The idea is to read strings from text file and include them in 2D dynamic array with constant number of columns and varying number of rows. If the initial number of rows is not enough to include all strings the memory block for the array has to be reallocated. The code is compiling OK but the execution is impossible.
#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));
}