如何修复用C编写的代码?

时间:2014-01-18 16:31:05

标签: c arrays text-files

它适用于20-20桌子,但对于其他任何事情它都会崩溃。 该文件位于以下链接中:http://www.csd.uoc.gr/~hy100/glid.txt。 我无法弄清楚问题是什么,因为当我把20-20表放在它的工作时间和时间 我给出了一张21-20的表,它能完美地完成这项工作,但在能够返回0之前崩溃了;

#include <stdio.h>
#include <stdlib.h>

int height, length;
char **world, **new_world;

int load_world_from_file(char filename[]) {

  int i, j;
  char ch;

  FILE *fp;
  fp = fopen(filename, "r");

  if (fp == NULL ) {
    perror("Error while opening the file.\n");
    exit(EXIT_FAILURE);
  }

  fscanf(fp, "%d %d", &height, &length);
  printf("here:%d,%d\n", height, length);
  /*dilosi dunamika tou pinaka kataxoriseis*/
  /* declaration under the table entries */
  world = (char **) malloc(sizeof(char *) * (height + 1));/*height + 1 ('\0')*/
  for (i = 0; i < 2 * height; i++) {
    /* height + height ('|') + 1    ('\0') */
    world[i] = (char *) malloc(sizeof(char) * (length + length + 1));
  }

  /* height + 1 ('\0') */
  new_world = (char **) malloc(sizeof(char *) * (height + 1));
  for (i = 0; i < 2 * height; i++) {
    /* height + height ('|') +  1 ('\0') */
    new_world[i] = (char *) malloc(sizeof(char) * (length + length + 1));
  }

  printf("The contents of %s file are :\n", filename);

  i = 0;
  j = 0;
  while ((ch = fgetc(fp)) != EOF) {
    i++;
    if (i = length + length + 1) {
      j++;
      i = 0;
    }
    world[j] = ch;
    printf("%c", world[j]);
  }
  printf("\n");
  for (i = 0; i < (((2 * length) + 2) * height) + 1; i++) {
    printf("%c", world[i]);
  }

  fclose(fp);
  return 0;
}

int main() {

  char filename[30], filename2[30];

  printf("Enter the name of file you want to open:\n");
  scanf("%s", &filename);

  load_world_from_file(filename);

  return 0;
}

非常感谢您的帮助。 IT

0 个答案:

没有答案