简体   繁体   English

将多维数组作为指针传递给函数

[英]Passing Multidimensional arrays to functions as Pointers

I have to pass two arrays ( A and B with dimensions of 5X4) to two functions called FUNCTION_1 and FUNCTION_2.我必须将两个数组(尺寸为 5X4 的 A 和 B)传递给两个名为 FUNCTION_1 和 FUNCTION_2 的函数。 Both of arrays columns and rows should be passed as POINTERS.数组列和行都应该作为 POINTERS 传递。 FUNCTION_1 will take each element of A array and calculate the sum of prime factors of each element located in A( (with the help of another function called sumPrime), then it will store these sums in array B. FUNCTION_2 has to print both of A and B arrays. ( The normal numbers array, and the prime factors sums array). There are some additions in the program which are not important now but I am going to show them too in respect of clearness. FUNCTION_1 将获取 A 数组的每个元素并计算位于 A( 中的每个元素的素因数的总和(在另一个名为 sumPrime 的函数的帮助下),然后它将这些总和存储在数组 B 中。 FUNCTION_2 必须打印两个 A和 B 数组。(正常数数组和素因数和数组)。程序中有一些添加,现在不重要,但为了清晰起见,我也将展示它们。

#include <stdio.h>
#include <stdlib.h>
#define ROW 5
#define COL 4
# include <math.h>
int sumPrime(int number){
     int factor = 2;
     int sum=0;

    while(1!=number){
       if(number%factor==0){
          number /= factor;
          sum+=factor;

          factor = 2;
          continue;
        }
        factor++;
    }

    return sum;
}
int FUNCTION_1(int *a[][20],int *b[][20],int row, int col){
    int c,d;
    for(c=0;c<row;c++){
        for(d=0;d<col;d++){
             b[c][d]=sumPrime(a[c][d]);
            return b[c][d];
        }
    }


}
void FUNCTION_2(int *x[][20],int *y[][20],int rows, int cols){
    printf(" \n A matrix is :\n");
    int e,f;
    for(e=0;e<rows;e++){
        for(f=0;f<cols;f++){
            printf("A[%d][%d] is %d\n",e,f,x[e][f]);



        }
    }
    printf("\n B matrix is:\n");
    for(e=0;e<rows;e++){
        for(f=0;f<cols;f++){
            printf("A[%d][%d] is %d\n",e,f,FUNCTION_1(x,rows,cols,y,rows,cols));



        }
    } 
}






int main(){


    int A[ROW][COL]={0};
    int B[ROW][COL]={0};
    int x=1;
    int i;
    int j;

    for(i=0;i<ROW;i++){

        for(j=0;j<COL;j++){
            A[i][j]=x;
            x=x+2;

        }                                   
    }
    printf("%d",A[0][0]);




    return 0;

}

When trying to perform FUNCTION_1 or FUNCTION_2 I get many errors or even when defining the functions.尝试执行 FUNCTION_1 或 FUNCTION_2 时,我收到很多错误,甚至在定义函数时也会出错。 There is no problem with defining A matrix or prime function!定义A矩阵或素函数都没问题! HELP!!帮助!!

您对矩阵的定义是错误的 .. 使用: func(int* a[20] , int cols)在这种情况下,您将有 20 行,或func(int a[][20] , int rows)并定义一些宏对于列,如果它是固定值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM