【问题标题】:Multidimensional array prototype error in CC中的多维数组原型错误
【发布时间】:2014-09-29 19:07:36
【问题描述】:

我在使用以下代码时遇到了一些问题。 它是制作一个函数,将一个多维数组的内容复制到另一个。 代码如下:

#include<stdio.h>
void copyarray(int ros,int cos,double ard[][cos] ,double arf[][cos]);
int main(){
    int rows,columns;
    printf("Enter number of rows\n ");
    scanf("%d",&rows);
    printf("Enter number of columns\n");
    scanf("%d",&columns);
    double ar[rows][columns];
    double ar1[rows][columns];
    printf("Enter the elements ");
    for(int i=0;i<rows;i++){
  for(int j=0;j<columns;j++){
      scanf("%lf",&ar[i][j]);
  }
    }
    printf("The 2d array is :\n");  

    for(int i=0;i<rows;i++){
  for(int j=0;j<columns;j++){
            printf("%lf ",ar[i][j]);        
  }
  printf("\n");
    }
    copyarray(rows,columns,ar,ar1); 
    return 0;
}

void copyarray(int r,int c,double ar[r][c],double arr1[r][c]){  
    for(int j=0;j<r;j++){
  for(int i=0;i<size;i++){
      arr1[j][i]=ar[j][i];
  }
    }
    printf("The new array has the following elements:\n");
    for(int j=0;j<r;j++){
  for(int i=0;i<size;i++){
      printf("%lf ",arr1[j][i]);
  }
  printf("\n");
    }
}

我收到以下错误:

“函数体外参数‘cos’的使用”

有人可以帮我解决这个问题吗? 谢谢

【问题讨论】:

    标签: c function multidimensional-array function-prototypes


    【解决方案1】:

    你有

    void copyarray(int ros,int cos,double ard[][cos] ,double arf[][cos]);
    

    这是

    type function_name(type arg_name_1,
                       type arg_name_2,
                       type array_name_1[][arg_name_2],
                       type array_name_2[][arg_name_2]);
    

    在 C99 之前,您不能在函数声明中使用参数(在本例中为 arg_name_2)。错误是指在array_name_2[][arg_name_2] 中使用它是“在函数体之外”。

    但是,如 HostileFork 所述,如果您使用的是符合 C99 标准(或更高版本)的编译器,则可以执行此操作。

    【讨论】:

    【解决方案2】:

    你有双重ard[][cos], double arf[][cos]

    你需要double *ard, double *arf

    因为c语言从来不是一个数组是传值的,只传链接

    您可以按值传递结构,但这是另一回事

    #include <stdio.h>
    
    void fill(int *a)
    {
            int i, j;
            for (i = 0; i < 10; i++) {
                    for (j = 0; j < 10; j++) {
                             a[i * 10 + j] = i + j;
                    }
            }
    }
    void print(int *a)
    {
            int i, j;
            for (i = 0; i < 10; i++) {
                    for (j = 0; j < 10; j++) {
                            printf("%2d ", a[i * 10 + j]);
                    }
                    printf("\n");
            }
    }
    
    int main(int argc, char *argv[])
    {
            int arr[10][10];
            fill(&arr[0][0]);
            print(&arr[0][0]);
            return 0;
    }
    

    可能不是很漂亮,但编译器的真正原因就很清楚了

    【讨论】:

    • 不,OP 写的内容是正确的,只要他们使用支持 VLA 的编译器。在任何情况下,T [n][m] 类型的表达式都不会衰减为T * 类型;它会衰减到输入T (*)[m]
    猜你喜欢
    • 2012-10-22
    • 1970-01-01
    • 2014-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-01
    • 2012-03-03
    • 1970-01-01
    相关资源
    最近更新 更多