0

Consider the code:

double func(double a[3])
{
    /* do something with a and return */
}

int main(void)
{
    std::vector<double> test(LARGE_NUM_DIVISIBLE_BY_3);
    for (size_t i = 0; i < LARGE_NUM_DIVISIBLE_BY_3 / 3; ++i)
    {
        test[3 * i] = /* some random double */;
        test[3 * i + 1] = /* some random double */;
        test[3 * i + 2] = /* some random double */;

        double val = func(&test[3 * i]);
    }
}

Is this defined behavior in C++11? I.e., can I pass a pointer (&test[3 * i]) to a function that expects an array (double func(double a[3]))? I know if I were to go the other way (i.e., pass an array to a function that expects a pointer), the array would decay to a pointer - does the reverse also work?

R_Kapp
  • 2,818
  • 1
  • 18
  • 32
  • No, `a` will not be returned, just used to calculate the return value – R_Kapp Jan 31 '19 at 16:59
  • You are saying array and showing vector. Is that what you meant? – Ant Jan 31 '19 at 17:00
  • @NathanOliver: I disagree with the duplicate tag - I want to know if the reverse situation of that question is legal, as I have already made explicit. – R_Kapp Jan 31 '19 at 17:02
  • And the dupe explains it is. `void by_value(const T* array) // const T array[] means the same` – NathanOliver Jan 31 '19 at 17:03
  • @NathanOliver: It actually explicitly states "when passing in an array" (whereas I want to pass in a pointer) right before that code block, but I'll believe you that it works the other way as well. That was my intuition, as well. – R_Kapp Jan 31 '19 at 17:05

1 Answers1

1

You can't really pass arrays like that. Any argument declaration like double a[] (with or without a size) is translated by the compiler as a pointer, double* a.

And arrays naturally decays to pointers to their first element. So if you have an actual array (and not a vector) like

double test[SOME_SIZE];

then passing it when a pointer is expected (like test) will pass a pointer to its first element (&test[0]).

For vectors that's not possible though, and you have to explicitly pass a pointer like you already do.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621