gpt4 book ai didi

c - 读取未知维度的矩阵

转载 作者:行者123 更新时间:2023-11-30 20:29:46 26 4
gpt4 key购买 nike

我正在尝试从以此方式格式化的文件中读取矩阵

1 2 3 44 5 6 78 9 10 11*1 0 10 1 11 1 1]

but I don't know how to pass the multidimensional array with its dimension given by rows[] and cols[] arrays to the function read_matrix().

I am able to get the correct dimension of the two matrices

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

int get_dim(char *file, int *r, int *col);
/*gets the dimension and type of operation*/

void read_matrix(char *file, int (*matA)[], int(*matB)[], int *m, int *n);

int main (int argc, char *argv[]){

int i,j;
int rows[2]= {0,1}; /* The last line of the file does not contain '\n' */
int cols[2]= {0,0};
int operation; /*type of operation 1 for * and 2 for + */

operation = get_dim(argv[1], rows, cols);

int A[rows[0]][cols[0]];
int B[rows[1]][cols[1]];

printf("A is a matrix %d x %d\n",rows[0], cols[0]);

if(operation != 0)
printf("B is a matrix %d x %d\n", rows[1], cols[1]);

read_matrix(argv[1], A, B, rows, cols);

/*printing the matrices */

for(i = 0; i < rows[0]; i++){
for(j=0; j < cols[0]; j++){
printf("%d ", A[i][j]);
}
printf("\n");
}

printf("*\n");

for(i = 0; i < rows[1]; i++){
for(j=0; j< cols[1]; j++){
printf("%2d ", B[i][j]);
}
printf("\n");
}
return 0;
}

int get_dim(char *file, int *r, int *col){

FILE *fp;
int c;
int op=0;
int n =0; /*to check all coefficients in a row */

/* opening file for reading */
fp = fopen(file, "r");

if(fp == NULL) {
perror("Error opening file");
}

while ( (c = getc(fp)) != ']')
{
if(isdigit(c) && n==0){
if(op == 0)
col[0]++;
else
col[1]++;
}

//Count whenever new line is encountered
if (c == '\n'){
n=1;
if(op == 0)
r[0]++;
else
r[1]++;
}

if(c == '*'){
op=1;
n =0;
c = getc(fp);
}
else if(c == '+'){
op=2;
c = getc(fp);
}

//take next character from file.
}
fclose(fp);
return op;
}

void read_matrix(char *file, int (*matA)[], int(*matB)[], int *m, int *n){

int i,j;
FILE *fp;

if( (fp = fopen(file, "r")) != NULL ){

for(i=0; i < m[0]; i++)
for(j=0; j < n[0]; j++)
fscanf(fp, "%d", &matA[i][j]);

/*skip the line containing the character operator */
while ( fgetc(fp) != '\n')
fgetc(fp);

for(i=0; i < m[1]; i++)
for(j=0; j < n[1]; j++)
fscanf(fp, "%d", &matB[i][j]);
}

fclose(fp);
}

我应该这样定义指针:int(*matA)[cols[0]] 和 int(*matB)[cols[1]]。在 read_matrix() 中,通过声明此指针: int(*matB)[] 我收到错误:无效使用具有未指定边界的数组,据我所知。但界限是由 get_dim() 函数确定的。

最佳答案

get_dim 函数的结果在运行时确定,而像 matA 这样的静态数组的大小必须在编译时确定。例如,采用以下代码:

volatile size_t length = 5;
int myArray[length];

或者另一个例子:

size_t length;
//take input from the user...
int myArray[length]

这些示例无法编译,因为长度只能在运行时确定。

您必须使用动态分配的数组来完成您想做的事情。

关于c - 读取未知维度的矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56364691/

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