[英]read text form a file into matrix in c using read
I currently try to fix a problem I encountered during a project. 我目前正在尝试解决在项目期间遇到的问题。 I have to read the content of a file (a map) into a matrix, but the first line contains 4 separate characters:
我必须将文件(地图)的内容读入矩阵,但是第一行包含4个单独的字符:
Code: 码:
#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);
}
You are returning pointer to local variable. 您正在返回指向局部变量的指针。 Local variables are removed from scope (their lifetime has ended) after returning from function, so accessing this address (which doesn't belong to you anymore) has undefined behavior.
从函数返回后,局部变量将从作用域中删除(它们的生命周期已经结束),因此访问此地址(不再属于您)具有未定义的行为。
Also this is declaration of pointer-to-array 这也是指针到数组的声明
char * res[BUF_S + 1];
+---+ +---+
| * |--------->| | res[0][0] (*ret)[0]
+---+ +---+
res | | res[0][1]
+---+
| | ...
+---+
| | res[0][BUF_S + 1 - 1]
+---+
If you apply this operation 如果您执行此操作
res[ret][0] = '\0';
with ret != 0
you are invoking undefined behavior. ret != 0
您正在调用未定义的行为。
You have to declare it like this ( pointer-to-pointer-to-char ) 您必须像这样声明它( 指针到指针到字符 )
char ** res = malloc(sizeof(char*) * X); // Where X is number of rows
And every row separately 和每一行分别
for (int i = 0; i < X; i++)
{
res[i] = malloc(BUF_S + 1);
}
Then you can access different 'rows' (max X-1
, X
and more would again lead to access outside of bounds and undefined behavior). 然后,您可以访问不同的“行”(最大
X-1
, X
和更多的行将再次导致访问超出界限和未定义的行为)。
Then you will free memory. 然后,您将释放内存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.