'How arrays with an empty size works in c++? [duplicate]

I'm reading some materials about C++ and I just saw that array can be declared without a size (ex. int arr[], char x[][10]) and I'm wondering how/when it's actually used. Could someone explain both examples, please?

A more explicit example:

void foo(char[][10]);

Does that mean that any array like a[n][10], a[m][10] can be passed to the above function?



Solution 1:[1]

Does that mean that any array like a[n][10], a[m][10] can be passed to the above function?

Yes. The function signature void foo(char[][10]); is allowed as long as you pass a compatible argument, i.e. a char array with 2 dimensions in which the second has size 10.

In fact, technically, the argument will decay to a pointer, so it's the same as having void foo(char (*)[10]);, a pointer to array of ten, in this case chars. An argument of type char[] will also decay, this time to a pointer to char (char*).


Furthermore omitting the first dimension of an array is permitted on declaration as long as you initialize it. The fist dimension of the array will be deduced by the compiler based on the initialization content, i.e.:

int arr[]{1,2};

will have size 2 (arr[2]) whereas

int arr[][2]{{1,2},{2,4}};

will become arr[2][2] based on the aggregate initialization.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1