0

I am reading this post [Function returning a pointer to an int array] and learning the difference between returning a pointer to int and a pointer to an array of int.
I got a few questions while trying to sum it up. First, take a look at this code (keeping it simple):

Functions test and test2 return pointer to int and a pointer to an array of int

int* test(size_t &sz) {
    int *out = new int[5];
    sz = 5;
    return out;
}

int (*test2())[3] {
    static int out[] = {1, 2, 3};
    return &out;
}

How do I have to change test2 to work with dynamic array (not static)? And is it possible to pass an array size as a reference or somehow?
Main function looks as this. The code compiles.

int main() {
    size_t sz;
    int *array = test(sz);
    for (size_t i = 0; i != sz; ++i) {
        array[i] = 10;
        cout << *(array + i) << " ";
    }
    cout << endl;    
    delete[] array;

    int (*array2)[3] = test2();
    for (size_t i = 0; i != 3; ++i) {
        cout << (*array2)[i] << " ";
    }
}

Result

10 10 10 10 10 
1 2 3 
user2376997
  • 501
  • 6
  • 22

1 Answers1

2

test2 does not return a pointer to a single int, but a pointer to a 3-element int array. I encourage you to try the wonderful https://cdecl.org/ website, enter int (*test2())[3] and see for yourself.

You probably tried to return new int[3] and it failed. That's because new[] returns a pointer to a single int (the first element of the dynamically allocated array), and a pointer to a single int is not automatically converted to a pointer to an entire array of many ints.

How do I have to change test2 to work with dynamic array (not static)?

Strictly technically speaking, like this:

int (*test2())[3] {
    return reinterpret_cast<int(*)[3]>(new int[3] { 1, 2, 3 }); // horrible code
}

And is it possible to pass an array size as a reference or somehow?

In the case of test2, the array's size is part of the type and thus fixed at compile time. You cannot change a type at runtime by passing a reference.


Now, seriously.

Nobody right in their mind writes code like this. new[] is already quite a broken language feature, and your extra obfuscation work with additional pointers, references and C syntax idiosyncrasies doesn't make it better. This is C++, use std::vector:

#include <iostream>
#include <vector>

std::vector<int> test() {
    return { 1, 2, 3 };
}

int main() {
    for (auto num : test()) {
        std::cout << num << " ";
    }
}
Christian Hackl
  • 27,051
  • 3
  • 32
  • 62