【问题标题】:Why do I get this error? Expected expresion before int为什么我会收到此错误? int 之前的预期表达式
【发布时间】:2018-02-12 08:44:06
【问题描述】:

我目前的问题是在 C 中找到方阵的转置。我使用的算法是创建一个二维数组来存储我想找出其转置的矩阵。然后我调用一个实际转置它的函数(因为数组是通过引用传递的),以便在调用函数后它被转置。 函数代码如下:-

//transpose of n by n matrix
#include<stdio.h>
void transpose(int arr[int][int]); //prototype declaration line 3
void transpose(int arr[int r][int c]){ //line 4
    int i,j;
    int matB[c][r];
    for(i=0;i<c;i++){
        for(j=0;j<r;j++){
            matB[i][j]=arr[j][i];
        }
    }
    for(i=0;i<r;i++){
        for(j=0;j<c;j++){
            arr[i][j]=matB[i][j];
        }
    }
}
int main(){
    int n,i,j;
    printf("enter the dimensions of square matrix :-");
    int mat[n][n];
    scanf("%d",n);
    printf("please enter the elements of the matrix :-->\n");
    for(i=0;i<n;i++){
        for(j=0;j<n;j++){
            scanf("%d",&mat[i][j]);
        }
    }
    transpose(mat);
    printf("the transpose of the given matrix is:- \n ");
    for(i=0;i<n;i++){
        for(j=0;j<n;j++){
            printf("%d\t",mat[n][n]);
        }
        printf("/n");
    }
}  

但我收到以下错误:-

第 3 行:-[错误] 'int' 之前的预期表达式
第 4 行:- [错误] 'int' 之前的预期表达式

第 3 行和第 4 行对应函数 void() 的原型声明和代码中的函数定义

我目前使用 DEV C++ 作为编译器.. 我的程序的快照:- click here to see the snapshot of my program

这里是我编译时遇到的错误:- click here to see the scanpshot of error i got

【问题讨论】:

  • 语法根本上是错误的。你必须研究数组和函数是如何工作的。我们无法在 SO 帖子中教给您所有这些内容,因为这个话题太宽泛了。

标签: c


【解决方案1】:

上面的代码sn-p有两个问题。

  1. 有关函数参数的语法错误。您不能在方括号内传递参数类型。
  2. 必须有恒定的列大小才能与参数列表中的数组一起传递。

你可以这样做。

#define R 10
#define C 100
void transpose(int arr[][C]); // prototype declaration line 2
void transpose(int arr[][C]) { // line 3
    int i, j;
    int matB[C][R];
    for (i = 0; i<C; i++) {
        for (j = 0; j<R; j++) {
            matB[i][j] = arr[j][i];
        }
    }
    for (i = 0; i<R; i++) {
        for (j = 0; j<C; j++) {
            arr[i][j] = matB[i][j];
        }
    }
}

【讨论】:

  • 为什么需要给出数组第二维的大小?? ..我已经创建了函数以一维数组作为参数的程序,但我从未在函数定义中提到一维数组的大小......为什么必须在二维数组中给出第二维的大小??
  • 我不确定,它到底是如何工作的,我有一段时间不做 C,但基本原理是关于分配,你在物理内存中没有矩阵,你可以想象它像一个行,因此每一列和每一行都像一个块一样分配。这就是为什么不能使 col / row 可变长度的原因。如果需要,您必须使用动态/手动分配并重新分配空间
【解决方案2】:

会的

#define R 10
void transpose(int (*arr)[R]); // prototype declaration line 2

void transpose(int arr[][R]); // prototype declaration line 2

R 应该是一个常数。如果不是 C99

void transpose(int r,int c, int (*arr)[r]){ // This will work as prototype 

然后

void transpose(int r,int c, int (*arr)[r]){ 
    ....
}

更清晰易用

void transpose(int r,int c, int arr[c][r]){

如果您不明白,请记住二维数组(数组的数组)转换为指向第一个元素的指针 - 第一个元素是一个数组,因此指向第一个元素的指针将是 int (*)[]。较早的解决方案由此而来。

例如,为了澄清之前的想法 - 传递一维数组同样的事情也成立。假设你有这个功能,

int a[10];
f(a);

...

void f(int a[])
or 
void f(int *a)

这里也发生了第一个元素的衰减。这不过是int*

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多