使用read读取文本在c中将文件形成矩阵

时间:2017-08-30 09:13:03

标签: c

我目前正在尝试修复项目中遇到的问题。我必须将文件(地图)的内容读入矩阵,但第一行包含4个单独的字符:

  1. 行数
  2. 空角色的代表
  3. 障碍人物的代表
  4. 完整角色的代表。这些我需要输入数组。
  5. 代码:

    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    #include <stdlib.h>
    #include "head.h"
    
    #define BUF_S 4096
    
    char    **ft_build_martrix(char *str, int *pr, int *pc, char *blocks)
    {
      int     fd;
      int     ret;
      int     ret2;
      int     j;
      char    *res[BUF_S + 1];
    
      j = 0;
      fd = open(str, O_RDONLY);
      if (fd == -1)
      {
          ft_putstr("map error");
      }
      ret2 = read(fd, blocks, 4); //take the first row out and put it into the array
      ret = read(fd, res, BUFF_S); //read the file's content into the matrix
      res[ret][0] = '\0';
      *pr = blocks[0] - '0'; // give the number of rows to the r variable that is declared in main and passed as argument, I think that's the equivalent of the $r in c++ ?
      blocks[0] = blocks[1]; // delete the
      blocks[1] = blocks[2]; // first character
      blocks[2] = blocks[3]; // that is already in *pr
      while (res[1][j] != '\n')
          j++;
      *pc = j; // get the number of column
      return (res);
    }
    

1 个答案:

答案 0 :(得分:0)

您正在返回指向本地变量的指针。从函数返回后,局部变量从范围中移除(它们的生命周期已经结束),因此访问该地址(不再属于您)具有未定义的行为。

这也是指向数组

的声明
char * res[BUF_S + 1];

+---+          +---+
| * |--------->|   | res[0][0] (*ret)[0]
+---+          +---+
 res           |   | res[0][1]
               +---+
               |   | ...
               +---+
               |   | res[0][BUF_S + 1 - 1]
               +---+

如果您应用此操作

res[ret][0] = '\0';

使用ret != 0,您正在调用未定义的行为。

你必须像这样声明它(指向指针的指针

char ** res = malloc(sizeof(char*) * X);  // Where X is number of rows

每一行分别

for (int i = 0; i < X; i++)
{
    res[i] = malloc(BUF_S + 1);
}

然后,您可以访问不同的“行”(最大X-1X,更多会再次导致访问边界和未定义的行为。

然后你将释放记忆。

相关问题