c - 读取未知维度的矩阵
问题描述
我正在尝试从以这种方式格式化的文件中读取矩阵
1 2 3 4 4 5 6 7 8 9 10 11 * 1 0 1 0 1 1 1 1 1]
但我不知道如何将由 rows[] 和 cols[] 数组给出的维度的多维数组传递给函数 read_matrix()。
我能够得到两个矩阵的正确维度
#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]
这些示例无法编译,因为长度只能在运行时确定。
您将不得不使用动态分配的数组来做您想做的事情。
推荐阅读
- json - Spark - JSON 空字符串数组显示为字符串
- ios - 在 Swift 中获取线程 1 信号 SIGABRT 崩溃错误
- python - 使用 TF-slim 训练的模型与 python 推理完美配合,但使用 C++ 给出完全错误的结果
- python - 如何在“stock.quant.tree”中添加字段
- javascript - 在构造函数中定义对象属性
- java - 将 SOAP 响应转换为 JAVA 对象
- haskell - 未能混合 {,non-} 无点函数定义子句
- php - 使用语言环境时未找到 404
- java - 如何在@Query 注释中使用参数的方法
- azure - Azure VM 加密:aadAppname