0

A function accepts a value of type int[][26], however, I am unable to define a variable of this type.

void A(int abc[][26]);

I have tried the following

int abc[][26] (can't compile)
int (*abc)[26] (segmentation fault)

How do I define such a variable/

Thanks a lot

Alexander Ho
  • 503
  • 2
  • 7
  • 18
  • Basically you don't. `int abc[][26]` will take and 2d array of `int[N][26]` – NathanOliver Nov 08 '19 at 17:23
  • OK I see, so I don't need to specifically define such an array – Alexander Ho Nov 08 '19 at 17:24
  • When you pass an array to a function, the size in the brackets is not enforced. Functionally, it is the same as passing a pointer. When you declare a variable, the size is important because the compiler needs to put it on the stack and needs to know how much space to reserve. That's why it worked when passed to the function, but not when you tried to declare a variable that way. – parktomatomi Nov 08 '19 at 17:31
  • @AlexanderHo Correct. I've added an answer to explain more in detail. – NathanOliver Nov 08 '19 at 17:31

2 Answers2

1

How do I define variable of type int[][26]?

int[][26] is an array of unknown bound. You cannot define variables of such type.

Arrays of unknown bound can are typically used in contexts where the type is adjusted to be something else. For example, in a function argument list, an array is adjusted to be a pointer to an element of such array. The following are equivalent due to type adjustment:

void A(int abc[][26]);
void A(int (*abc)[26]);
// adjusted argument type is int(*)[26]

Another example of such adjustment is definition of a variable, where the bound is deduced from the initialiser. The following are equivalent due to type adjustment:

int arr[][26]  = {{}, {}};
int arr[2][26] = {};
// adjusted array type is int[2][26]

A use case for arrays of unknown bound where the type is not adjusted is in templates, where explicitly providing such array as template type argument can be used to signify that a pointer is to an element in an array, rather than a singular object. For example, std::allocator<int>::deallocate will invoke delete while std::allocator<int[]>::deallocate will invoke delete[].

eerorika
  • 232,697
  • 12
  • 197
  • 326
1

Basically you don't. int abc[][26] will take any 2d array of the form int[N][26].

When you work with arrays as function parameters the array decays to a pointer. That means the top most dimension is not needed since it decays to a pointer of the type of elements in the array. So, if you have

void foo(int[10])

what you really have is

void foo(int*)

since it doesn't matter how many elements there are. When you have

void foo(int[10][26]) 
//or
void foo(int[][26]) 

then you get

void foo(int(*)[26])

Since the array holds arrays we get a pointer to an array since it doesn't matter how many arrays the pointer points to, we just need to know it points to a int[26].

NathanOliver
  • 171,901
  • 28
  • 288
  • 402