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

时间:2016-03-25 20:24:47

标签: c arrays pointers matrix

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

我的任务是下一步:用C m x n维度写一个程序,从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])

此功能的参数也是在我的任务中预定义的,所以我必须遵循它们。

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

5 个答案:

答案 0 :(得分:0)

这些将是你的函数原型:

        Alamofire.request(.GET,"https://randomuser.me/api/").responseJSON{
        (response) -> Void in
        if let json = response.result.value{
            print(json["results"]["user"]["name"])
        }

因为你正在调用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*

答案 1 :(得分:0)

我添加了评论以帮助您完成代码。

#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);
}

答案 2 :(得分:0)

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: %d\n", *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: %d\n", *ptcount);

        free(array);

        return 0;
    }

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

答案 3 :(得分:-1)

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


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

你就是这样做的。

答案 4 :(得分:-1)

这是一个给出3D数组

的例子
int buffer[5][7][6];

位置[2][1][2]的元素可以buffer[2][1][2]*( *( *(buffer + 2) + 1) + 2)进行访问。

Reference