L M
L M

Reputation: 29

Sending the pointer of each row of a matrix to a function

I am learning memory allocation in C. I want to create a matrix of [10][20] using malloc such that each row is sent to a function to be processed. Is it enough to send only the pointer of each row? i.e. *arr[0];

The following is a chunk of my code:

#include <stdio.h>
#include <stdlib.h>

int **arr; // Buffer

int sumElements(int *arr[]){
 // do something
}


void main(){
    int i,j;
    arr = malloc(10 * sizeof(int *)); // Allocate # of rows for the matrix

        for(i = 0; i < 10; i++){
            arr[j]= malloc(20 * sizeof(int)); // Allocate # of entries in each row
            sumElements(*arr[j]); // send the current row to be processed by function
        }

}

Upvotes: 1

Views: 110

Answers (1)

dbush
dbush

Reputation: 223972

The current row is not *arr[j], but arr[j]. The former is of type int while the latter is of type int *. So sumElements should be passed a int [] or int *, not a int *[].

So the function definition should be:

int sumElements(int arr[])

And you should call it like this:

sumElements(arr[j]);

Upvotes: 4

Related Questions