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).
Related
This question already has answers here:
Why sizeof(param_array) is the size of pointer?
(8 answers)
Closed 9 months ago.
I am trying to find the smallest missing element of an array using function check, which has two arguments (n and array A). I can't understand why my function check is always returning one and the while loop is never closing.
#include <stdio.h>
bool check(int n, int A[])
{
for (int i = 0; i < sizeof(A); i++)
{
if(A[i] == n)
{
return 1;
}
}
return 0;
}
int main()
{
int A[] = {1, 3, 6, 4, 1, 2};
int n = 1;
while (check(n, A) == 1)
{
n++;
}
printf("%d is missing",n);
}
The compiler adjusts a parameter having an array type to pointer to the array element type.
So this function declaration
bool check(int n, int A[])
is equivalent to
bool check(int n, int *A );
And within the function the expression sizeof(A) is equivalent to the expression sizeof( int * ) and is equal to either 4 or 8 depending on the used system.
Thus this for loop
for (int i = 0; i < sizeof(A); i++)
invokes undefined behavior.
I know but still that's not why the while loop is never stopping.
Answering your above comment it seems that in the used system sizeof( int * ) is equal to 8 and the variable n is placed in memory after the array A as they defined in main
int A[] = {1, 3, 6, 4, 1, 2};
int n = 1;
As a result you get the infinite wile loop because in the for loop within the function the memory occupied by the variable n is checked and n is always equal to itself.
Thus the function always returns 1.
That is in the for loop the array is traversed as it has 8 elements like
int A[] = {1, 3, 6, 4, 1, 2, n, some_indeterminate_value };
I have the following program.
#include <stdio.h>
double getAverage(int *arr[], int size) {
int i, sum = 0;
double avg;
for (i = 0; i < size; ++i)
{
printf("%d %d\n", i, arr[i]);
sum = sum + arr[i];
}
printf("%d\n", sum);
avg = (double)sum / size;
return avg;
}
int main ()
{
/* an int array with 5 elements */
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
/* pass pointer to the array as an argument */
avg = getAverage( balance, 5 ) ;
/* output the returned value */
printf("Average value is: %f\n", avg );
return 0;
}
It's output is not correct. When I print the *arr[] values, the are not the same as the balance value. Do you know why and how I can fix this program?
0 1000
1 3
2 50
3 0
4 0
256992
Average value is: 51398.400000
Your function is declared like
double getAverage(int *arr[], int size)
That is, the first argument is supposed to be an array of pointers to int.
Then you call it as
getAverage( balance, 5 )
where balance is an array of int, which decays to a pointers to its first element (i.e. balance is equal to &balance[0]). This have the type int *.
The two types are mismatching, which the compiler should have warned you about.
The solution is to fix the function argument:
double getAverage(int *arr, int size)
The problem is here:
double getAverage(int *arr[], int size) {
You're passing a pointer to an array. That decays to a double pointer (a int**). You're using it like an int*, however. As a result, the pointer arithmetic under the hood is wrong. Change it to this:
double getAverage(int arr[], int size) {
It looks like on your setup, the pointers are twice as big as your ints, which is why it's always skipping a value (and ends up accessing invalid memory in the end).
If your compiler did not issue any warning for this code, try to see if you can set it to be more strict with warnings.
I'm working on some C homework for class and I've been running into issues using arrays. Here is a sample of one of my functions that's having an error.
void multiply(int a, int size)
{
int i;
for(i = 0; i < size; i++){
a[i] = a[i] * 5;
printf("%d, ", a[i]);
}
printf("\n");
}
It returns the error: subscripted value is neither array nor pointer nor vector on lines 5 & 6 when I call for a[i]. I have a as an array with size 10, but each time I try and call an individual value in the array it doesn't want to work. I've tried searching it but none of the solutions really seems to work.
You should change your function to:
void multiply(int * a, int size)
Change your function header to:
void multiply(int* a, int size)
Othewise the function thinks a is an int not an int array
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.
Greetings,
I am trying to learn pointers in C, I simply want my "addtwo" function to add 2 to every element of the input integer array, yet I get odd compilation errors, here is the non-pointer version which indeed won't properly compile.
addtwo(int *arr[]) {
int i=0;
for(;i< sizeof(arr)/sizeof(int);i++) {
arr[i] = arr[i] + 2;
}
}
main() {
int myarray[] = {1,2,3,4};
addtwo(myarray);
}
Regards
You've some problems. First, you try to pass a int* to a parameter that's type int**. That won't work. Give it type int*:
void addtwo(int *arr){
int i=0;
for(;i< sizeof(arr)/sizeof(int);i++){
arr[i] = arr[i] + 2;
}
}
Then, you need to pass the size in an additional argument. The problem is, that when you pass arrays, you really pass just a pointer (the compiler will make up a temporary pointer that points to the array's first element). So you need to keep track of the size yourself:
void addtwo(int *arr, int size){
int i=0;
for(;i<size;i++){
arr[i] = arr[i] + 2;
}
}
int main(void) {
int myarray[] = {1,2,3,4};
addtwo(myarray, sizeof myarray / sizeof myarray[0]);
}
Now it will work. Also put the return type before them. Some compilers may reject your code, since it doesn't comply to the most recent C Standard anymore, and has long been deprecated (omitting the return type was the way you coded with the old K&R C).
addtwo(int *arr[]) should be addtwo(int *arr)
You cannot use sizeof to get the size of an array from a pointer. Typically you would either pass the size of the array as a separate arg or have some special value marking the last element.
Not to do with the compile error, but...
You have to pass sizeof(arr) to the function instead of calling it in the function. When an array is passed to a function, C no longer sees it as an array, but as a single pointer to memory, so that sizeof(arr) as you are calling it now, will return the size of the pointer arr, which is most likely 4.
Here's what I mean in code:
void addtwo(int *arr, int size){
int i=0;
for(;i< size;i++){
arr[i] = arr[i] + 2;
}
}
int main(){
int myarray[] = {1,2,3,4};
addtwo(myarray, sizeof(arr)/sizeof(int));
return 0;
}
In C a notation int *arr[] is the same as int** arr.
You need to pass a pointer to the first element of the array and the array size. Array types decay to pointers in the context of function parameters. Try:
void addtwo(int *arr, size_t size){
for(size_t i = 0; i < size; i++){
arr[i] = arr[i] + 2;
}
}
int main() {
int v[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
addtwo(v, sizeof v / sizeof v[ 0 ]);
return 0;
}
Though others already gave the correct response, basically you have an array of pointers when you have
int *arr[]
I doubt that is what you want. If you have
int arr[]
then that will also be equivalent to
int *arr
addtwo argument declaration really reads:
arr is an array of pointers to integer
when you probably really want
a pointer to an array of integers
"How to Read C Declarations" has really helped me to grok the topic a while ago, maybe it will do the same for you.