1

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?

Ion
  • 81
  • 1
  • 9
  • do you mean something like `int arr[] = {1,2,3};` ? – 463035818_is_not_an_ai May 06 '22 at 12:49
  • I know that the syntax is valid but how is it used? – Ion May 06 '22 at 12:54
  • "_I'm reading some materials about C++_": The material (if it is supposed to be teaching material) should explain it. In either case, please provide a more concrete example of the kind of code you saw. There are multiple contexts in which you might see such types and each will probably have a somewhat different answer. But I am sure that there are duplicates around for each of these individual situations. The currently linked duplicate considers variable declarations of such types without initializers, which is not the common case. – user17732522 May 06 '22 at 12:55
  • 1
    foo got issue that it doesn't "know size" of array. It's as if you was passing a pointer to int[10], only a sugared syntax. – Swift - Friday Pie May 06 '22 at 13:03
  • 2
    In a parameter list, `char[][10]` is equivalent to `char (*) [10]`; a pointer to an array of ten `char`s. That is, it's not an array but a pointer. – molbdnilo May 06 '22 at 13:06

1 Answers1

3

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.

anastaciu
  • 23,467
  • 7
  • 28
  • 53