Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C: why the pointer type not compatible?

I have compilation error of "incompatible pointer type" with the following code.

f(unsigned char** arr)
{
   unsigned char* p = *arr;
}

int main()
{
   unsigned char a[31];
   f(&a);
}

I would like to understand why and how to fix.

Edit

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Sorry, I omit one point.

When I compile with gcc, it is only a warning, but g++ raises it as error.

cannot convert ‘unsigned char (*)[31]’ to ‘unsigned char**’`

I want to fix the error when using g++.

>Solution :

a is an array of 31 unsigned char (unsigned char[31]).

&a is a pointer to such an array (unsigned char (*)[31]).

You’re trying to "assign" this to arr, which is a pointer to a pointer to an unsigned char.

&a does not point to a pointer. &a is not compatible with unsigned char **.


Usual approach: (Pointer to first element)

void f( unsigned char *arr ) {
   unsigned char *p = arr;
}

int main( void ) {
   unsigned char a[31];
   f( a );  // Short for `f( &(a[0]) )`.
}

Alternate approach: (Pointer to the array)

void f( unsigned char (*arr)[31] ) {
   unsigned char *p = *arr;    // Short for `p = &((*arr)[0])`.
}

int main( void ) {
   unsigned char a[31];
   f( &a );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading