首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么我会有这个错误?期望值

为什么我会有这个错误?期望值
EN

Stack Overflow用户
提问于 2018-02-12 08:44:06
回答 2查看 5.5K关注 0票数 1

目前,在C.The算法中,我遇到了一个寻找方阵转置的问题,我使用的是创建一个二维数组来存储我想要找出的转置矩阵。然后,我调用一个实际转换它的函数(因为数组是通过引用传递的),这样在调用函数之后,它就会被转置。该功能的代码如下:

代码语言:javascript
复制
//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++作为编译器。我的程序的快照:- 单击此处查看我的程序的快照

以下是编译时遇到的错误:- 点击这里查看我得到的错误扫描。

EN

回答 2

Stack Overflow用户

发布于 2018-02-12 08:54:09

在上面的代码片段中有两个问题。

  1. 函数参数的语法是错误的。不能在正方形大括号内传递参数类型。
  2. 必须与参数列表中的数组一起传递常量列大小。

你可以做这样的事。

代码语言:javascript
复制
#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];
        }
    }
}
票数 2
EN

Stack Overflow用户

发布于 2018-02-12 08:46:46

它将是

代码语言:javascript
复制
#define R 10
void transpose(int (*arr)[R]); // prototype declaration line 2

代码语言:javascript
复制
void transpose(int arr[][R]); // prototype declaration line 2

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

代码语言:javascript
复制
void transpose(int r,int c, int (*arr)[r]){ // This will work as prototype 

然后

代码语言:javascript
复制
void transpose(int r,int c, int (*arr)[r]){ 
    ....
}

更清晰易用

代码语言:javascript
复制
void transpose(int r,int c, int arr[c][r]){

如果您不知道,2d数组(数组数组)将转换为指向第一个元素的指针--第一个元素是一个数组,因此指向第一个元素的指针将是int (*)[]。从那时起,早期的解决方案就出现了。

例如,为了澄清前面的想法--传递一个单维数组,同样的事情也是如此。假设你有这个函数,

代码语言:javascript
复制
int a[10];
f(a);

...

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

问题是,这里也发生了第一个元素的衰变。除了int*什么都不是。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48742428

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档