如何通过C中的指针访问矩阵数组的元素



我似乎找不到任何关于如何通过函数中的指针访问数组元素的信息,我尝试了以下多个答案,但似乎都不适用。

我的任务是下一步:用m x n维的C编写一个程序,其中元素从0到9随机生成。使用两个新函数计算偶数元素的和,并计算等于零的元素数。

#include <stdio.h>
#include <stdlib.h>
void SumEven(int *a, int n, int m, int *sum){
}
void EqualToZero(int *a, int n, int m, int *number){
}
int main()
{
    int** a;
    int m, n, l, i, j, r, sum;
    printf("Enter number of columns for matrix: ");
    scanf("%d", &m);
    printf("Enter number of rows for matrix: ");
    scanf("%d", &n);
    a = (int **) malloc(m*sizeof(int));
    for (l = 0 ; l < m ; l++){
        a[l] = (int **) malloc(n*sizeof(int));
    }
    time_t t;
    srand((unsigned)time(&t));
    printf("n");
    printf("Your matrix is:n");
    printf("n");
    for(i = 0 ; i < m ; i++){
        for(j = 0 ; j < n ; j++){
            r = rand() % 10;
            a[i][j] = r;
            printf("%d ", r);
        }
        printf("n");
    }
    printf("n");
    SumEven(&a, n, m);
    return(0);
}

正如您在所提供的代码中看到的,我将这些函数留空,因为我不知道如何将矩阵传递给它们并访问它们的元素,这样我就可以打印结果。

此外,我为函数本身的逻辑编写的伪代码是:

if(a[i][j] % 2 == 0)
     printf("%d ", a[i][j])

 if(a[i][j] == 0)
     printf("%d ", a[i][j])

此外,函数的这些参数是在我的任务中预定义的,所以我必须遵循它们。

EDIT:我也不知道我是否将相同的矩阵传递给具有SumEven(&a, n, m);的函数。我尝试输出矩阵的地址,并使用printf("%d", &a)显示来自main()SumEven()函数的地址。

This code may help. It does the following:
1. For an arbitrary array of integers, sum the elements of the array 
   - using a pointer to the SUM function
2. For an arbitrary array of integers, count the number of zero elements in
   the array - using a pointer to the COUNTZERO function

    #include <stdio.h>
    #include <stdlib.h>
    // sum the elements of the matrix
    void sum(int* arr, int rows, int cols, int* result)
    {
        int sum = 0;
        int i, j;
        for (i = 0; i < rows; i++) {
            for (j = 0; j < cols; j++) {
                sum = sum + arr[i*cols + j];
            }
        }
        *result = sum;
    }
    // count the number of zero elements in the matrix
    void countZero(int* arr, int rows, int cols, int* result)
    {
        int count = 0;
        int i, j;
        for (i = 0; i < rows; i++) {
            for (j = 0; j < cols; j++) {
                if (arr[i*cols + j] ==0) count = count + 1;
            }
        }
        *result = count;
    }

    // arbitrary initialisation of 2D array of ints (force last entry of the array to equal zero - for testing purposes)
    void init2D(int *arr, int rows, int cols) {
        int i, j;
        for (i = 0; i < rows; i++) {
            for (j = 0; j < cols; j++) {
                arr[i*cols + j] = 1;
            }
        }
        // use this to test the countZero function
        arr[(rows-1)*(cols-1)] = 0;
    }
    int main() {
        int *array;     // will hold a 2D array of integers
        int N = 10;     // arbitrary number of rows     
        int M = 5;      // arbitrary num cols
        // 2D array of integers expressed as one "contiguous row" of memory 
        // make sure your indexing is correct when referenceing the array for  (i,j)th element
        array = (int*)malloc(sizeof(int)*N*M);
        if (array != NULL) {
            init2D(array, N, M);
        }
        // the function pointer
        void(*general)(int*,int,int,int*);   
        // will contain the sum result
        int sumAll = 0;
        int* ptsumAll = &sumAll;
        // make the function pointer point to the sum function
        general = &sum;
        // sum the contents of the array
        general(array,N,M, ptsumAll);
        printf("sum of array elements: %dn", *ptsumAll);
        // contains a count of the zero elements in the array
        int count =0;
        int* ptcount = &count;
        // make the function pointer point to the count function
        general = &countZero;
        // count the number of zero element in the array
        general(array, N, M,ptcount);
        printf("number of zeros: %dn", *ptcount);
        free(array);
        return 0;
    }

一些参考文献:https://www.cs.swarthmore.edu/~newhall/unixhelp/C_arrays.htmlhttp://www.cprogramming.com/tutorial/function-pointers.html

我添加了注释来帮助您编写代码。

#include <stdio.h>
#include <stdlib.h>
void SumEven(int *a, int n, int m, int *sum){
    //put this statement in 2 nested for loops of size n and m
     if(a[i][j] % 2 == 0)
        sum += a[i][j];
}
void EqualToZero(int *a, int n, int m, int *number){
    //put this statement in 2 nested for loops of size n and m
      if(a[i][j] == 0)
           number++;
}
int main()
{
int** a;
int m, n, l, i, j, r, sum;
printf("Enter number of columns for matrix: ");
scanf("%d", &m);
printf("Enter number of rows for matrix: ");
scanf("%d", &n);
a = (int **) malloc(m*sizeof(int));
//should be m*sizeof(int*)
for (l = 0 ; l < m ; l++){
    a[l] = (int **) malloc(n*sizeof(int));
    //should be cast as (int*)
} 
//I suggest you take look at declaring 2d arrays in C 
time_t t;
srand((unsigned)time(&t));
printf("n");
printf("Your matrix is:n");
printf("n");
for(i = 0 ; i < m ; i++){
    for(j = 0 ; j < n ; j++){
        r = rand() % 10;
        a[i][j] = r;
        printf("%d ", r);
    }
    printf("n");
}
printf("n");
SumEven(&a, n, m);
//need to pass &sum to this function. Also make sure it is initialized to 0
//call EqualToZero() function with proper parameters.
return(0);
//return 0; not return(0);
}

这些将是您的函数原型:

void SumEven(int **a, int n, int m,int *sum);
void EqualToZero(int **a, int n, int m,int *number);

由于您正在从调用传递a(双指针),因此应该有一个双指针(int **a)来接收它。

呼叫:

SumEven(a, n, m,&sum);
EqualToZero(a, n, m,&number);

这就是你如何访问函数中的数组:

void SumEven(int **a, int n, int m,int *sum){
    int i,j,tsum=0;
    for(i = 0 ; i < m ; i++){
        for(j = 0 ; j < n ; j++){
            if(a[i][j] % 2 == 0)
            {
                tsum+=a[i][j];
                printf("%d ",a[i][j]);
            }
        }
    }
    *sum=tsum;
}

此外,此行a[l] = (int **) malloc(n*sizeof(int));("int**"到"int*"的赋值)中存在错误,应为a[l] = (int *) malloc(n*sizeof(int));

下面是一个例子,给定一个3D阵列

int buffer[5][7][6];

位置[2][1][2]处的元素可以作为buffer[2][1][2]*( *( *(buffer + 2) + 1) + 2)来访问。

参考

if(( *(*(a + i) + j) % 2 ) == 0 )
     printf("%d", *(*(a + i) + j) )

if( *(*(a + i) + j) == 0 )
     printf("%d", *(*(a + i) + j) )

这就是你的做法。

最新更新