我有這個程序的問題。這個想法是從文本文件中讀取字符串,並將它們包含在具有恆定列數和不同行數的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