[英]Passing Multidimensional arrays to functions as Pointers
我必須將兩個數組(尺寸為 5X4 的 A 和 B)傳遞給兩個名為 FUNCTION_1 和 FUNCTION_2 的函數。 數組列和行都應該作為 POINTERS 傳遞。 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;
}
嘗試執行 FUNCTION_1 或 FUNCTION_2 時,我收到很多錯誤,甚至在定義函數時也會出錯。 定義A矩陣或素函數都沒問題! 幫助!!
您對矩陣的定義是錯誤的 .. 使用: func(int* a[20] , int cols)
在這種情況下,您將有 20 行,或func(int a[][20] , int rows)
並定義一些宏對於列,如果它是固定值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.