gpt4 book ai didi

c - sscanf 在未知大小的矩阵上的用法?

转载 作者:太空宇宙 更新时间:2023-11-03 23:23:32 24 4
gpt4 key购买 nike

所以,我有一个包含 NxM 大小矩阵的文件。例如:

P2
3 3 1
1 0 0
0 1 0
0 0 1

'P2'只是一个无用的指标,第一个'3'表示有多少列,第二个'3'表示有多少行,'1'表示矩阵数字中的最大值。该矩阵存储在如下数据结构中:

typedef struct {
int c; // columns
int l; // lines
unsigned char max; // max value
unsigned char** data // variable to store matrix's numbers
} Matrix;

为了将文件中的数字存储到数据变量中,我使用了 fread 函数,如下所示:

Matrix* newMatrix = NULL;
newMatrix = malloc(sizeof(Matrix));

FILE* fp = NULL;
fp = fopen(matrixfile, "r");

long size;
fseek(matrixfile, 0, SEEK_END);
size = ftell(matrixfile);
newMatrix->data = malloc(size);

// Jump the 'P2' bytes.
fseek(matrixfile, 2, SEEK_SET);

// Get the c, l and max values.
fscanf(matrixfile, "%i %i %i", &newMatrix->c, &newMatrix->l, &newMatrix->max);

// Jump a '\n' character.
fseek(matrixfile, 1, SEEK_CUR);

// Get matrix's numbers.
fread(newMatrix->data, 1, size, matrixfile);

好的,我将矩阵的数字作为字符串存储在“unsigned char** data”变量中。但现在我需要处理这些数字,所以我试图将这个字符串转换为整数矩阵。我试图做这样的事情:

void StringtoInt (Matrix* str){

int matrixAux[str->l][str->c], i, j;
for(i=0; i<str->l; i++)
for(j=0; j<str->c; j++)
sscanf(str->data, "%i ", &matrixAux[i][j]);
}

好吧,我明白为什么这不起作用以及为什么我的“matrixAux”将是一个只有 1 的 CxL 矩阵。但是在不知道矩阵中有多少元素的情况下,我想不出任何方法来使用 sscanf。

那么,我的问题是:是否有更好的方法将“unsigned char** 数据”字符串转换为整数矩阵而不更改“数据”类型 (unsigned char**)?

我想也许我只是使用了错误的方法将文件的矩阵存储到数据变量(fread 函数)中,或者弄乱了指向指针语法的指针。但我也没有看到任何其他好的选择来做到这一点。

最佳答案

问题 1:计算data的大小

如果矩阵存储为文本文件,就像你发布的一样,使用

fseek(matrixfile, 0, SEEK_END);
size = ftell(matrixfile);

提出数据的大小是不正确的。

你所要做的就是读取行数和列数,然后,你可以使用 numRows * numCols 得出 data 的大小.

问题 2:为 data 分配内存

使用

newMatrix->data = malloc(size);

data 分配内存似乎表明缺乏对内存分配方式的理解。

数据的类型是char**

malloc(size) 为大小为 size 的字符数组分配内存。将 malloc(size) 的返回值分配给 newMatrix->data 是错误的。

你需要的是:

newMatrix->data = malloc(numRows*sizeof(char*)); // Assuming you read numRows first.
for ( int i = 0; < numRows; ++i )
{
newMatrix->data[i] = malloc(numCols);
}

读取数据

现在您可以使用以下方法从文件中读取数据:

for ( int i = 0; < numRows; ++i )
{
for ( int j = 0; j < numCols; ++j )
{
int number;
if ( fscanf(matrixfile, "%d", &number) == 1 )
{
// Check that number is within range.
// ...

newMatrix->data[i][j] = number;
}
else
{
// Unable to read the number.
// Deal with the error.
exit(1);
}
}
}

关于c - sscanf 在未知大小的矩阵上的用法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32958291/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com