所以我编写了这段代码,以便使用malloc函数从文件中读取矩阵。它似乎将矩阵保存在内存中,但是当我尝试打印它时,会出现这个带有Access违规读取位置的弹出窗口。我是编程和IDK的新手如何解决这个问题(我留下了程序退出的评论)......
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int **mat(int **&m, int &i, int*&v) {
FILE *f = fopen("in.txt", "r");
i = 0;
int j;
char buffer[100];
while (!feof(f)) {
m = (int**) malloc(100 * sizeof (int**));
j = 0;
m[i] = NULL;
fgets(buffer, 100, f);
char*tok;
tok = strtok(buffer, " \n");
while (tok) {
m[i] = (int*) malloc(50 * sizeof (int*));
m[i][j] = (int) malloc(sizeof (int));
m[i][j] = atoi(tok);
j++;
tok = strtok(NULL, " \n");
}
v[i] = (int) malloc(sizeof (int));
v[i] = j;
i++;
}
return m;
}
void print(int**&m, int &i, int*&v) {
for (int k = 0; k < i; k++) {
for (int l = 0; l < v[k]; l++) {
printf("%d ", m[k][l]); // The issue appears here
}
printf("\n");
}
}
void main() {
int**m, i, *v;
v = (int*) malloc(20 * sizeof (int));
//v = NULL;
m = mat(m, i, v);
print(m, i, v);
system("pause");
}
答案 0 :(得分:0)
这不是一个真正的答案,但不适合作为评论。
很抱歉,但几乎所有您对malloc
的使用都不正确,无论是您使用它们的方式还是 您首先使用它。< / p>
我会尝试从
开始int main()
{
int mat[100][50];
int i;
int v[20];
然后尝试编写没有malloc
的代码。您拥有所需的所有int
,并且不必单独分配。
另一件事是feof(f)
没有告诉下一次读取是否会成功,但会告诉我们先前的读取是否失败。在while
条件下不是很有用,因为它触发一轮太晚了。检查fgets
返回的内容要好得多。
答案 1 :(得分:0)
我发现自己是一个答案,我把它放在这里
int **mat(int **&m, int &i, int*&v) {
FILE *f = fopen("in.txt", "r");
i = 0;
int j;
char buffer[100];
while (!feof(f)) {
m = (int**) realloc(m, (i+1) * sizeof (int*)); // Changed aloocation type and saw that i wrote sizeod(int**) instead of int*
j = 0;
m[i] = NULL;
fgets(buffer, 100, f);
char*tok;
tok = strtok(buffer, " \n");
while (tok) {
m[i] = (int*) realoc(m[i], (j+1) * sizeof (int)); // Changed aloocation type and saw that i wrote sizeod(int**) instead of int*
m[i][j] = (int) malloc(sizeof (int));
m[i][j] = atoi(tok);
j++;
tok = strtok(NULL, " \n");
}
v[i] = (int) malloc(sizeof (int));
v[i] = j;
i++;
}
return m;
}