Pointer to an array pointer

The following is a snippet of code. I want to know if line no. 17 line no. 17 correct and correct casting in c?

 #include <stdio.h> typedef int twoInts[2]; void print(twoInts *twoIntsPtr); void intermediate (twoInts twoIntsAppearsByValue); int main () { twoInts a; a[0] = 0; a[1] = 1; print(&a); intermediate(a); return 0; } void intermediate(twoInts b) { print((int(*)[])b); // <<< line no. 17 <<< } void print(twoInts *c){ printf("%d\n%d\n", (*c)[0], (*c)[1]); } 

Also, when I change the definition of intermediate to

 void intermediate(twoInts b) { print(&b); } 

I get below compilation warnings, but o / p is not suitable.

 1.c:17:11: warning: passing argument 1 of print from incompatible pointer type print(&b); ^ 1.c:5:6: note: expected int (*)[2] but argument is of type int ** void print(twoInts *twoIntsPtr); 

According to my understanding, the array decays to pointer to int in the funtion argument. What is the reason?

+5
source share
1 answer

a is an array. Therefore, when you pass it to intermediate() , it is converted to a pointer to its first element (otherwise called "array attenuation").

So b in:

 void intermediate(twoInts b) { print(&b); } 

is of type int* , not int[2] , as you might expect. Therefore, &b is of type int** , not int (*)[2] , as expected by the print() function. Therefore, the types do not match.

If you change intermediate() to:

 void intermediate(twoInts *b) { print(b); } 

you won’t need to pass the address &b and it will be as expected and the types will match correctly.

+3
source

Source: https://habr.com/ru/post/1233691/


All Articles