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 – sizeof arrays in function decleration

I’ve been given this code:

void f1(int** p1);
void f2(int p2[][]);
void f3(int p3[3][5]);

we can assume that sizeof(int) = 4, sizeof(void*) = 8
and I needed to choose all the correct answers from these answers:

  1. sizeof(p3) == 3*8, sizeof(*p3) == 5*4, sizeof(**p3) == 4
  2. sizeof(p2) == 8, sizeof(*p2) == 8, sizeof(**p2) == 4
  3. sizeof(p1) == 8, sizeof(*p1) == 8, sizeof(**p1) == 4
  4. sizeof(p1) == 8, sizeof(*p1) == 8, sizeof(**p1) == 8
  5. sizeof(p3) == 8, sizeof(*p3) == 8, sizeof(**p3) == 4
  6. sizeof(p3) == 8, sizeof(*p3) == 5*4, sizeof(**p3) == 4
  7. sizeof(p2) == 8, sizeof(*p2) == 8, sizeof(**p2) == 8

so I chose answers no. 2, 3, 6 and I was correct on 3 and 6, but 2 was wrong.
Would be glad for explanation why 2 is wrong, and only 3 and 6 are correct.

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

>Solution :

This declaration of the parameter

void f2(int p2[][]);

is invalid in C. The right most subscript operator must have an expression.

You could write for example

void f2(int p2[*][*]);

but in this case you may not dereference pointers. Such a declaration may be present only in a function declaration that is not a function definition.

Instead you could write for example

void f2( size_t n, int p2[*][n]);

In this case within the function sizepf( p2 ) will be equal to 8, sizeof( *p2 ) will be equal to n * sizeof( int ) and **p2 will be equal to sizeof( int ).

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