【发布时间】:2017-09-12 17:08:42
【问题描述】:
所以我正在尝试从文件中读取矩阵(我确信有比我这样做更好的方法来做到这一点)。我很难弄清楚如何从文件中读取每个单词(即矩阵的每个条目),因此决定读取每一行并使用我在 stackexchange 中找到的名为 strtok 的东西。
我的main()内部是这样的
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <malloc.h>
#include <time.h>
#include <string.h>
int main(){
FILE *f;
int nmatrix=3;
int nmax=3;
int something;
int number, count, count2, i, j;
srand(time(NULL));
size_t len = 0;
ssize_t read;
char * line = NULL;
char * pch;
int ia;
int (*B)[nmatrix][nmatrix] = malloc(nmatrix * nmatrix * sizeof(int));
while(nmatrix<=nmax){
// Creation of Matrix
f = fopen("matrix.txt", "w");
for(count = 1; count <= nmatrix; count ++){
for(count2 = 1; count2 <= nmatrix; count2 ++){
number = rand()%9;
fprintf(f, "%s%d ", " ", number);
}
fprintf(f, "%s\n", " ");
}
fclose(f);
// Reading Matrix
f = fopen("matrix.txt", "r");
i=0;
while((read = getline(&line, &len, f)) != -1) {
printf("%s\n", line);
pch = strtok(line," ,.-");
j=0;
while (pch != NULL & j<nmatrix){
ia= (int)*pch-48;
*B[i][j]= ia;
pch = strtok(NULL, " ,.-");
j=j+1;
}
i=i+1;
}
fclose(f);
nmatrix=nmatrix+1;
}
return 0;
}
终端中的第一个输出是*B[i][j]= ia; 行是否被擦除,第二个输出是它。第一个输出读取文件中的所有行,第二个不读取最后一个。为什么? (输出看起来不同,因为矩阵是随机生成的)。
我对一切都很陌生,特别是指针,所以如果没有正确使用任何东西,我会很感激评论。
【问题讨论】:
-
请提供minimal reproducible example。虽然我很高兴看到初学者使用正确的矩阵类型:2D 数组,但是如果您使用指向 1D 数组的指针,您可以让您的生活更轻松。我有时已经回答过这样的问题,你可能想查看我的个人资料::answers。
-
你没有为
line分配memory这就是程序崩溃的原因,首先分配内存来存储line中的string。 -
好的,我现在把整个代码放好,至少现在如果有人想运行它,他们不必创建文件(代码创建它)。
-
@krpra,你为什么说没有错误就崩溃了?不知道你在说什么,我首先必须分配内存来存储字符串,请你说得更具体些。
-
@krpra 不,请RTF
getline()M 如果*lineptr是空指针或*lineptr指向的对象大小不足,则应分配对象malloc()或对象应被重新分配,就像分别由realloc()一样,使得对象足够大以容纳要写入它的字符