У меня проблема с получением расширенной матрицы из текстового файла. Программа просто выдаст ошибку после успешного считывания всех данных из текстового файла, скорее всего, потому, что она все еще ищет другой токен для достижения или fgets() не достигает состояния NULL? Я честно потерялся...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "apmatrix.h"
#define NUMARGS 2
#define BUFSIZE 128
int main (int argc, char *argv[])
{
/* Matrices that will always be used */
Matrix* A;
Vector* b;
Vector* x;
iVector* p;
/* Used in LU factorization */
Matrix* L;
Matrix* U;
/* Standard character read-in variables needed */
char sep[] = " "; /* parsing separator is space */
char *z,*buffer; /* buffer and pointer to scan buffer */
FILE *ifp; /* source file */
unsigned buflen; /* length of line read */
int flag, count;
int Rows,Columns;/* to hold number read */
int CurrentRow=0;
/* first check to see if have required number for argc */
/* if not, error has occurred, don't do anything else */
if (argc == 2 || argc==3)
{
/* correct number of arguments used, try to open both files */
buffer = (char*) malloc(BUFSIZE); /* allocate buffer */
ifp = fopen (argv[1], "r"); /* open file for reading */
if (ifp && buffer) { /* if successful proceed */
/* read file line by line */
flag=0;
while (fgets(buffer, BUFSIZE, ifp) != NULL) {
/* defensive/secure programming */
buflen = strlen(buffer);
/* parse line */
z = strtok(buffer,sep);
/* take in the values of the rows and columns */
if(flag == 0){
++flag; /* Flag = 1 */
Rows = atoi(z); /* Convert the string to double */
printf(" %d",Rows);
z = strtok(NULL, sep); /* find next number */
Columns = atoi(z); /* Convert the string to double */
printf(" %d",Columns);
putchar('\n');
A = m_alloc(Rows,Columns);
b = v_alloc(Rows);
x = v_alloc(Rows);
p = iv_alloc(Rows);
L = m_alloc(Rows,Columns);
U = m_alloc(Rows,Columns);
}
/* take in the values of the matrices */
else{
for(int i = 0; i < Rows; i++){
A->mat[CurrentRow][i] = (Real) atof(z); /* Convert the string to an int*/
z = strtok(NULL, sep); /* find next number */
printf(" %2.3f ",A->mat[CurrentRow][i]);
}
b->vec[CurrentRow] = (Real) atof(z); /* Convert the string to an int */
printf(" %2.3f ",b->vec[CurrentRow]);
putchar('\n');
CurrentRow++;
putchar('\n');
}
}
fclose (ifp);
...
Я не распечатывал остальную часть своего кода, потому что просто не вижу, чтобы он имел отношение к рассматриваемому вопросу. Я хочу знать, почему возникает эта проблема и как я могу исправить ее в коде, потому что мне понадобится информация для решения Ax=b позже в программе. Текстовый файл дает мне расширенную матрицу [A|b], поэтому я решаю для x, используя факторизацию LU. Я думаю, что это может быть связано с самим буфером, но я также неопытен в программировании на C.
Также текстовый файл, который я читаю, написан как таковой...
3 4
2 1 1 1
6 2 1 -7
-2 2 1 7
Это результаты, которые я получаю от кода
3 4
2.000 1.000 1.000 1.000
6.000 2.000 1.000 -7.000
-2.000 2.000 1.000 7.000
Segmentation fault (core dumped)
Спасибо за ваше время. :)
ОБНОВЛЕНИЕ: я попытался запустить gdb для отладки, и я застрял, пытаясь запустить дамп ядра с текстовым файлом. (например, ./hw6 ge1.txt — это то, что я ввожу в командную строку). Как мне запустить это с текстовым файлом, потому что без него он segfaulting.
c
Continuing.
Expecting two or three arguments
The second argument must be a text file to read from.
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400a4e in m_free (M=0x0) at apmatrix.c:32
32 free(M->mat[0]); /* free data */
z = strtok(NULL, sep); Columns = atoi(z);
не проверяет,z === NULL
. - person chux - Reinstate Monica   schedule 16.04.2015