我有这个程序的问题。这个想法是从文本文件中读取字符串,并将它们包含在具有恒定列数和不同行数的2D动态数组中。如果初始行数不足以包含所有字符串,则必须重新分配数组的内存块。代码编译正常,但执行是不可能的。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));
}
这功课吗? – batbrat 2010-02-06 13:45:44