Search code examples
c++arraysfunction-declaration

How to call a function with this parameter: fun(Ty param[NUM])?


In an API header file I found a strange function declaration:

void API_GetParameter(API_SOMESTRUCT param[API_NUM_CONST]);

where API_NUM_CONST is an enum value and API_SOMESTRUCT is a struct, so my guess is that param is an array of that struct.

The function thus expects an existing data field which it fills or changes. I cannot say what the API function does internally.

Right now, my code looks like this:

API_SOMESTRUCT *param = new API_SOMESTRUCT[API_NUM_CONST];
API_GetParameter(param);
// ... read out param
delete[] param;
param = NULL;

But I suspect this piece of code to be responsible for a heap corruption error I'm recently getting and I'm not sure if my call is correct.


I understand function headers with non-const arrays for parameters that look like this:

void fun(int *arr); // expects a pointer to a non-const int array of arbitrary size...
  • So what is the exact meaning of the API function declaration?
  • Is param being called by value or by reference?
  • And how do I correctly call that function?

Solution

  • Declaration void f(int x[3]); is the same as void f(int *x); So, the function needs to receive a valid pointer to API_SOMESTRUCT. Otherwise, you can't know what it is going to do, how many elements it expects, or what it is going to do with them. You have to read the documentation.

    If I had to guess, I would have passed in an array of API_NUM_CONST elements, just allocated on the stack:

    API_SOMESTRUCT param[API_NUM_CONST]
    API_GetParameter(param);
    // use param