2

I recently saw a function written in the following form void func(int size, int a[size]){ ... } and I was curious about the argument a[size]. At first I thought maybe it had something to do with indexing the array, but running the code a was in fact an array. Then I thought maybe it had to do with the size of the array, so I tried passing in different value and seeing if it would affect the array length, but it seemed not to (unless maybe it had something to do with writing past the array, but this feels unlikely). So my question is essentially, what does the "index" do in the function arguments?

4
  • @DavidRanieri It's not a VLA if it's a function parameter. Commented Oct 2, 2019 at 19:05
  • @Barmar well, it's a VLA used as function parameter, but it's a VLA, isn't it? Commented Oct 2, 2019 at 19:09
  • @DavidRanieri No, it's just equivalent to int *a. The size is ignored. Commented Oct 2, 2019 at 19:10
  • @Barmar you are right! Commented Oct 2, 2019 at 19:19

1 Answer 1

4

It's the array size, but it's ignored when it's in a function parameter declaration. A function parameter of the form int a[size] or int a[] is treated identically to int *a, because arrays decay to pointers when used as function arguments.

So it's essentially just a form of self-documentation. The caller is supposed to pass an array that contains size elements.

Note that this only applies to the first dimension in a multidimensional array parameter. If you have something like

void func(int width, int height, int a[height][width]) { ... }

The width part of the array declaration is used, but the height is ignored. a is a pointer to an array of int[width] rows; the width is needed when indexing the first dimension.

Sign up to request clarification or add additional context in comments.

1 Comment

You're right. I had the parameters in the wrong order.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.