0

I am trying to implement a function that takes an array, calculates 1/X for each element, and returns the resulting array.

However, I have an issue when trying to determine the size of each array. sizeof(X) / sizeof(X[0]) does not correctly calculate the array size, and instead outputs 0.

double* MyFunction(double X[]) {
    std::cout << "arraySize of x: " << sizeof(X) / sizeof(X[0]);
    double A[100] = {};
    for (int i = 0; i < sizeof(X) / sizeof(X[0]); ++i) {
        A[i] = 1 / X[i];
    }
    return A;
}

What am I doing wrong?

ApRD
  • 17
  • 1
  • 5
  • 3
    `return A;` is bad because it is returning a pointer to non-static local array, which is invalidated on returning and cannot be used after returning. You should use [`std::vector`](https://en.cppreference.com/w/cpp/container/vector) instead of arrays. – MikeCAT Mar 16 '21 at 14:05
  • 1
    `double* MyFunction(double X[])` is a slightly obfuscated way to write `double* MyFunction(double* X)`. You need to pass the size along with the pointer or use a proper container – 463035818_is_not_an_ai Mar 16 '21 at 14:08
  • Related: [What is array to pointer decay?](https://stackoverflow.com/questions/1461432/what-is-array-to-pointer-decay) – Drew Dormann Mar 16 '21 at 14:11

0 Answers0