0

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.

  • 4
    `p2` is an invalid declaration - none of the given answers for `p2` are correct. `p2[][]` does not translate to `**p2`. – John Bode Jun 21 '22 at 17:18
  • `int p3[3][5]` can be given as `int p3[][5]` but only the outermost dimension can be omitted. Otherwise the compiler won't know how to index the supposed array. – Weather Vane Jun 21 '22 at 17:21
  • 1
    "c - sizeof arrays" --> With `void f1(int** p1); void f2(int p2[][]); void f3(int p3[3][5]);`, none of `p1, p2, p3` are _arrays_. `p1, p3` are _pointers_. `p2` does not compile. Arrays are not pointers. Pointers are not arrays. – chux - Reinstate Monica Jun 21 '22 at 17:39
  • And see [**C sizeof a passed array**](https://stackoverflow.com/questions/5493281/c-sizeof-a-passed-array), along with the question it's linked to. – Andrew Henle Jun 21 '22 at 17:41

1 Answers1

2

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

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335