Passing two-dimensional array to a function by refrence (C Programming) [duplicate] - c

This question already has answers here:
Manipulate multidimensional array in a function
(4 answers)
Closed 8 years ago.
I'm learning pointers, and gotten stuck for an hour now, with this code,
#include <stdio.h>
int determinant(int **mat) /* int mat[3][3] works fine.. int *mat[3] doesn't.. neither does int *mat[] */
{
int det;
int a=*(*(mat+0)+0); // printf("\n%d",a);
int b=*(*(mat+0)+1); // printf("\n%d",b);
int c=*(*(mat+0)+2); // printf("\n%d",c);
int d=*(*(mat+1)+0); // printf("\n%d",d);
int e=*(*(mat+1)+1); // printf("\n%d",e);
int f=*(*(mat+1)+2); // printf("\n%d",f);
int g=*(*(mat+2)+0); // printf("\n%d",g);
int h=*(*(mat+2)+1); // printf("\n%d",h);
int i=*(*(mat+2)+2); // printf("\n%d",i);
det = a*(e*i-h*f) - b*(d*i-g*f) + c*(d*h-e*g);
return det;
}
int main()
{
int mat[3][3];
int i,j;
printf("Enter the 3 X 3 matrix:\n\n");
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
scanf("%d",*(mat+i)+j);
}
}
printf("\nThe determinant of the given 3 X 3 matrix is %d",determinant(mat));
return 0;
}
I don't think anything is wrong with the function call. Maybe the problem is while accepting the arguments. Idk, isn't mat a pointer to an 1-dimensional array, which would again be a pointer to the array element, making mat a pointer to a pointer?
When I print some text at places (just to check), i find that the execution goes till after int det in the function, and the program crashes in the next step.
mat [3][3] works well, but i wanna use some * there, because as i said, i'm 'learning'..
Please help!
Thanks :)

The correct prototype for your function is
int determinant(int mat[][3]);
or
int determinant(int (*mat)[3]);
(both are equivalent because of a special rule for arrays as function arguments)
Then you can simply access your matrix elements with something like mat[i][j].

This is because 2 dimensional array and pointer to pointer are not same.
No matter how much dimension does an array have, its 1 dimensional in actual memory. So we can access it serially.
#include <stdio.h>
#include <conio.h>
int determinant(int *matrix1stMember)
{
int a, b, c, d, e, f, g, h, i;
a = *(matrix1stMember + 0);
b = *(matrix1stMember + 1);
c = *(matrix1stMember + 2);
d = *(matrix1stMember + 3);
e = *(matrix1stMember + 4);
f = *(matrix1stMember + 5);
g = *(matrix1stMember + 6);
h = *(matrix1stMember + 7);
i = *(matrix1stMember + 8);
return ( a*(e*i-h*f) - b*(d*i-g*f) + c*(d*h-e*g) );
}
int main()
{
int matrix[3][3]; // int matrix[y][x]; not [x][y]
int i, j;
printf("\nEnter 3x3 Matrix : ");
for(j = 0; j < 3; j++)
{
for(i = 0; i < 3; i++)
{
scanf("%d", &matrix[j][i]);
}
}
// call function determinant(int*) using first member of array
printf("\nDeterminant = %d", determinant(&matrix[0][0]));
getch();
return 0;
}
If we have to access via row and column then we can do following
data = *(_1stMemberofArray + rowIndex*totalColumn + columnIndex);
For Example,
data = matrix[2][1];
where datatype of matrix is
int matrix[3][3];
is identical to.
data = *(matrixPointer + 2*3 + 1);
where 3 is total column 2 is row(vertical or y) and 1 is column(horizontal or x).
and datatype of matrixPointer is,
int* matrixPointer;
and it should point to first member of matrix;

2D array dont decay to pointer to pointer. You can decay them to pointers so your code should look like
int determinant(int *mat) {
int det;
int a=*((mat+0)+0); // printf("\n%d",a);
int b=*((mat+0)+1); // printf("\n%d",b);
int c=*((mat+0)+2); // printf("\n%d",c);
int d=*((mat+1*3)+0); // printf("\n%d",d);
int e=*((mat+1*3)+1); // printf("\n%d",e);
int f=*((mat+1*3)+2); // printf("\n%d",f);
int g=*((mat+2*3)+0); // printf("\n%d",g);
int h=*((mat+2*3)+1); // printf("\n%d",h);
int i=*((mat+2*3)+2); // printf("\n%d",i);
det = a*(e*i-h*f) - b*(d*i-g*f) + c*(d*h-e*g);
return det;
}
The above code is just for illustration, showing how 2-D array decays to 1-D array.
When you try to access the array using braces like a[2][1] then compiler does is unfolding for you. By unfolding I mean, the multiplication by sizeof(type) (as shown above multiply by 3). So if you decaying to 1-D you have to do it yourself.
One more thing to add, always pass the size of the dimension to the function who is has to tread the 1-D array as 2-D. like
int determinant(int *mat, int cols, rows);
Edit 1:
Just to add that #JensGustedt ans is also ok if you want to keep the arrays intact across function calls.

The correct signature for the function would be
int determinant(int mat[][3])
or
int determinant(int (*mat)[3])
In the context of a function parameter declaration, T a[] and T *a are exactly equivalent.
With either option, you can subscript mat normally in the function as you would in main:
int a = mat[0][0];
int b = mat[0][1];
...
Since a subscript operation implicitly dereferences the pointer (a[i] == *(a + i)),
you don't have to do the explicit dereference dance, making your code easier to read and understand (and potentially faster; I've seen some compilers generate more instructions for *(*(a + i) + j) than a[i][j], but don't rely on that being true everywhere).
Remember that when an expression of "N-element array of T" appears in most contexts, it is converted to an expression of type "pointer to T" and its value is the address of the first element in the array. Since the expression mat in the call to printf has type "3-element array of 3-element arrays of int", it is replaced with an expression of type "pointer to 3-element array of int".

If we pass a multidimensional array to a function:
int a2[5][7];
func(a2);
We can not declare that function as accepting a pointer-to-pointer
func(int **a) /* WRONG */
{
...
}
The function ends up receiving a pointer-to-an-array, not a pointer-to-a-pointer.

Related

Getting a pointer to a 2d Array

I need to get a pointer to a 2D array. The sizes ARE known at compile time if that helps. I need to perform an action a certain array based on the incoming value of a variable.
//Global arrays
// int c[6000][1000];
// int a[6000][1000];
void fun(int x){
//Setup a pointer here
//Possible solution: int (*pointer)[6000][1000];
int **pointer;
if (x == 0){
pointer = c;
}
else{
pointer = a;
}
//Modify pointer here and have changes reflect back to the array it was based off of
pointer[0][17] = 42;
}
I have looked at close to a dozen different stack overflow articles on how to do this but I cannot find a way to just a get a simple pointer to a 2D array.
//Global arrays
int c[6000][1000];
int a[6000][1000];
void fun(int x) {
int (* ptr)[1000];
if (x == 0) {
ptr = c;
} else {
ptr = a;
}
ptr[0][17] = 42;
}
Like this
//Global arrays
int c[6000][1000];
int a[6000][1000];
void fun(int x) {
if (x == 0) {
c[0][17] = 42;
} else {
a[0][17] = 42;
}
}
Accessing a 2D array using Pointers:
2D array is an array of 1D arrays which implies each row of a 2D array is a 1D array. So, think about two of your global arrays,
int c[6000][1000] and int a[6000][1000].
We can say c[0] is the address of row 0 of the first global 2D array. Similarly a[6000] is the address of row 6000 of the second global 2D array.
Now you want to find the c[0][17] and point that using a pointer which is basically, c[0][17] = *(c[0] + 17).
Also you can write for any other array elements, c[0] = *c and in general each element as, c[i][j] = *(c[i] + j) = ((c+i) + j).
So, if c is a 2D array of integer type then we can think that c is a pointer to a pointer to an integer which can be interpreted as int **c. Dereferencing *c gives you the address of row 0 or c[0] which is a pointer to an integer and again dereferencing c[0] gives you the first element of the 2D array, c[0][0] which is an integer.
You can test your code by accessing each element using pointer for a better understanding:
#include<stdio.h>
#include<stdlib.h>
//Global arrays
int c[6000][1000];
int a[6000][1000];
void fun(int x){
//Setup a pointer here
//Possible solution: int (*pointer)[6000][1000];
int (*pointer)[1000];
if (x == 0){
pointer = c;
}
else{
pointer = a;
}
//Modify pointer here and have changes reflect back to the array it was based off of
pointer[0][17] = 42;
}
int main(){
int num;
scanf("%d", &num);
fun(num);
if(num == 0){
printf("When num is %d, c[0][17] = %d\n", num, *(*(c) + 17));
}
else{
printf("When num is %d, a[0][17] = %d\n", num, *(a[0] + 17));
}
return 0;
}

In block swap algorithm for else case how come arguments for leftrotate are arr+n-d

I'm unable to interpret how come we are giving arr [] as arr+n-d in the leftrotate function. The comment HERE marks the line I'm talking about.
Block swap algorithm:
void printArray(int arr[], int size);
void swap(int arr[], int fi, int si, int d);
void leftRotate(int arr[], int d, int n)
{
if(d == 0 || d == n)
return;
if(n-d == d)
{
swap(arr, 0, n-d, d);
return;
}
if(d < n-d)
{
swap(arr, 0, n-d, d);
leftRotate(arr, d, n-d);
}
else
{
swap(arr, 0, d, n-d);
leftRotate(arr+n-d, 2*d-n, d); // HERE
}
}
void swap(int arr[], int fi, int si, int d)
{
int i, temp;
for(i = 0;i<d;i++)
{
temp = arr[fi + i];
arr[fi + i] = arr[si + i];
arr[si + i] = temp;
}
}
http://www.geeksforgeeks.org/block-swap-algorithm-for-array-rotation/
Whenever you pass an array as a parameter, only the address of that array is passed. You can read about this here
Suppose you have declared an array arr as int arr[] = {1,2,3,4,5,6,7,8,9,10};
Now if you call printf(arr); It returns the base address of arr (address of starting element of array)
If you type printf(arr[i]) the compiler interprets arr[i] as *(arr + i) and returns the value at address arr + i.
Arrays in C\C++ are accessed using pointer arithmetic.
Now coming to your question:
leftRotate(arr+n-d, 2*d-n, d); // HERE
We recursively call leftRotate() because we have shifted the B part of array with Al. Now the B part is at its final location and we can forget about it.
We now focus our attention on arr starting from element arr[n-d] to put those elements at their correct place.
So, the first argument of above function gives the address of element arr[n-d] and like dave_thompson_085 commented it's a bad practice because the type of that argument is not explicitly mentioned.
The second argument gives us the number of elements remaining to be shifted and the third argument gives us the size of array.
You can read more about arrays and pointers here:
Difference between pointer and array in C
Pointer vs Array in C
Arrays, String Constants and Pointers

Find max element in a matrix [duplicate]

This question already has answers here:
How to pass 2D array (matrix) in a function in C?
(4 answers)
Closed 6 years ago.
I've got this homework. Basically, what I have to do is complete the following code that returns the maximum element of a bidimensional array of 'r' rows and 'n' columns.
#include <stdio.h>
int max_element(int **A, int r, int n) {
// complete the code
int max;
max = a[0][0];
for (int i = 0; i < r; i++) {
for (int j = 0; j < n; j++) {
if (A[i][j] > max)
max = A[i][j];
}
}
return max; }
// implement a main() function to test the algorithm
int main() {
int A[2][3] = { {1, 0, 4}, {10, 3, 1} };
printf("%d\n", max_element(&A, 2, 3));
return 0; }
I have 1 warning:
passing argument 1 of 'max_element' from incompatible pointer type [-Wincompatible-pointer-types]
The console stopped working: a problem caused the program to stop working correctly...
Your max_element function is defined as such:
int max_element(int **A, int r, int n);
It takes a pointer to a pointer to int (int**) and you are feeding it this:
int A[2][3];
max_element(&A, 2, 3);
Do you expect the expression &A to yield a result of type int**? It will not. It will in fact yield a result of type int(*)[2][3]. That will not bind to int**. This is where the compiler warning kicks in. Those are incompatible pointers!!
You have a wider problem though. A 2D array is not int**. It has type int[][COLS]. You must specify the second number.
Change your function to be:
const int COLS = 3;
int max_element(int A[][COLS], int r, int n);
and then call as:
max_element(A, 2, 3);
Change the function prototype of max_element from:
int max_element(int **A, int r, int n)
To
int max_element(int A[][3], int r, int n)
This C-Faq thoroughly explains why. The gist of it is that arrays decay into pointers once, it doesn't happen recursively. An array of arrays decays into a pointer to an array, not into a pointer to a pointer.
And also, you should call max_element by max_element(A, 2, 3) instead of max_element(&A, 2, 3).
If a function is already declared as accepting a pointer to a pointer (as in your case), it is almost certainly meaningless to pass a two-dimensional array directly to it. An intermediate pointer would have to be used when attempting to call it with a two-dimensional array:
int max_element(int **A, int r, int n);
int *ip = &A[0][0];
max_element(&ip, 2, 3); /* PROBABLY WRONG */
but this usage is misleading and almost certainly incorrect, since the array has been flattened (its shape has been lost).

what's the difference between int (* f [])(); and int f[]();

i find this in Pointers on C
int f[](); /* this one is illegal */
and:
int (* f [])(); /* this one legal. */
i really want know what's the usage of the second one.
thank you.
The second example is quite valid, if you use initialization block. For example:
#include <stdio.h>
int x = 0;
int a() { return x++ + 1; }
int b() { return x++ + 2; }
int c() { return x++ + 3; }
int main()
{
int (* abc[])() = {&a, &b, &c};
int i = 0,
l = sizeof(abc)/sizeof(abc[0]);
for (; i < l; i++) {
printf("Give me a %d for %d!\n", (*abc[i])(), i);
}
return 0;
}
I'm not sure if the second example is legal, since the size of the function array is not known, but what it is supposed to be is an array of function pointers, and here is a possible example of usage if the size would be known:
int a()
{
return 0;
}
int main(int argc ,char** argv)
{
int (* f [1])();
f[0] = a;
}
int f[](); // this is illegal because of you can't create array of functions . It's illegal in C
But second is legal
int (* f [])(); It says that f is an array of function pointers returning int and taking unspecified number of arguments
int f[](); /* this one is illegal */
That's trying to declare an array of functions, which is impossible.
int (* f [])(); /* this one NOT legal, despite what the OP's post says. */
That's trying to declare an array of function pointers, which would be perfectly legal (and sensible) if the array size were specified, e.g.:
int (* f [42])(); /* this one legal. */
EDIT: The type int (* f [])() can be used as a function parameter type, because for function parameter types, array-to-pointer conversion takes place immediately, meaning we don't ever need to specify the dimension of the innermost array of a (possibly multidimensional) array:
void some_func(int (* f [])()); /* This is also legal. */

Define a matrix and pass it to a function in C

I want to create a program in which I can pass a matrix to a function using pointers.
I initialized and scanned 2 matrices in the void main() and then I tried to pass them to a void add function. I think I am going wrong in the syntax of declaration and calling of the function. I assigned a pointer to the base address of my matrix. (for eg: int *x=a[0][0], *y=b[0][0]). What is the right declaration? How can I specify the dimensions?
Given a 2D array of
T a[N][M];
a pointer to that array would look like
T (*ap)[M];
so your add function prototype should look like
void add(int (*a)[COLS], int (*b)[COLS]) {...}
and be called as
int main(void)
{
int a[ROWS][COLS];
int b[ROWS][COLS];
...
add(a, b);
However, this code highlights several problems. First is that your add function is relying on information not passed via the parameter list, but via a global variable or symbolic constant; namely, the number of rows (the number of columns is explicitly provided in the type of the parameters). This tightly couples the add function to this specific program, and makes it hard to reuse elsewhere. For your purposes this may not be a problem, but in general you only want your functions to communicate with their callers through the parameter list and return values.
The second problem is that as written, your function will only work for matrices of ROWS rows and COLS columns; if you want to add matrices of different sizes within the same program, this approach will not work. Ideally you want an add function that can deal with matrices of different sizes, meaning you need to pass the sizes in as separate parameters. It also means we must change the type of the pointer that we pass in.
One possible solution is to treat your matrices as simple pointers to int and manually compute the offsets instead of using subscripts:
void add (int *a, int *b, size_t rows, size_t cols)
{
size_t i;
for (i = 0; i < rows; i++)
{
size_t j;
for (j = 0; j < cols; j++)
{
*(a + cols * i + j) += *(b + cols * i + j);
}
}
}
and call it like so:
int main(void)
{
int a[ROWS][COLS] = {...};
int b[ROWS][COLS] = {...};
int c[ROWS2][COLS2] = {...};
int d[ROWS2][COLS2] = {...};
...
add(a[0], b[0], ROWS, COLS);
add(c[0], d[0], ROWS2, COLS2);
...
}
The types of a[0] and b[0] are "COLS-element arrays of int"; in this context, they'll both be implicitly converted to "pointer to int". Similarly, c[0] and d[0] are also implicitly converted to int *. The offsets in the add() function work because 2D arrays are contiguous.
EDIT I just realized I was responding to caf's example, not the OP, and caf edited his response to show something very similar to my example. C'est la guerre. I'll leave my example as is just to show a slightly different approach. I also think the verbiage about passing information between functions and callers is valuable.
Something like this should do the trick.
#define COLS 3
#define ROWS 2
/* Store sum of matrix a and b in a */
void add(int a[][COLS], int b[][COLS])
{
int i, j;
for (i = 0; i < ROWS; i++)
for (j = 0; j < COLS; j++)
a[i][j] += b[i][j];
}
int main()
{
int a[ROWS][COLS] = { { 5, 10, 5} , { 6, 4, 2 } };
int b[ROWS][COLS] = { { 2, 3, 4} , { 10, 11, 12 } };
add(a, b);
return 0;
}
EDIT: Unless you want to specify the dimensions at runtime, in which case you have to use a flat array and do the 2D array arithmetic yourself:
/* Store sum of matrix a and b in a */
void add(int rows, int cols, int a[], int b[])
{
int i, j;
for (i = 0; i < rows; i++)
for (j = 0; j < cols; j++)
a[i * cols + j] += b[i * cols + j];
}
#caf has shown a good code example.
I'd like to point out that:
I assigned a pointer to the base
address of my matrix. (for eg: int
*x=a[0][0],*y=b[0][0]).
You are not assining a pointer to the base of the matrix. What this does is assign to the value pointed by x and y, the base value in a and b respectively.
The right way would be
int (*x)[] = a;
int (*y)[] = b;
or alternatively
int *x = &a[0][0];
int *y = &b[0][0];

Resources