How to fix this code written in C?

萝らか妹 提交于 2019-12-24 20:07:19

问题


It works perfectly well for a 20-20 table but for anything else it crashes. the file is in this link:http://www.csd.uoc.gr/~hy100/glid.txt. I can not figure out what the problem is because when I put an 20-20 table it works and when I give a 21-20 table it does the job perfectly fine but crashes before being able to return 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;
}

Your help is much appreciated. IT

来源:https://stackoverflow.com/questions/21206749/how-to-fix-this-code-written-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!