Home > Mobile >  c - sizeof arrays in function decleration
c - sizeof arrays in function decleration

Time:06-22

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.

CodePudding user response:

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 ).

  • Related