Hello,

How to call a function which takes dynamic array argument? That is to say, if I have:

void fctn (int *a[], int n)
{
*a = &n;
//do stuff with a.
}

How to call this in main? Must I have another array declared in main to call it with?

Thanks for the help.

Dani AI

Generated

The declaration used in the first post is asking for an array of int pointers (the compiler treats that parameter as a pointer-to-pointer). Passing or assigning the address of a local (for example doing *a = &n inside the function) will create a dangling pointer when the function returns — that is unsafe. For details on how array parameters behave and decay to pointers see Array-to-pointer conversion.

As hinted, if the function really needs "an array of int pointers" the caller must provide an array (or pointer) of int* values and ensure each pointer is valid for the lifetime required:

void fctn(int** ptrs, std::size_t n) {
    for (std::size_t i = 0; i < n; ++i)
        if (ptrs[i]) /* use *ptrs[i] safely */;
}

int main() {
    const std::size_t N = 3;
    int** ptrs = new int*[N];
    for (std::size_t i = 0; i < N; ++i) ptrs[i] = new int(static_cast<int>(i + 1));
    fctn(ptrs, N);
    for (std::size_t i = 0; i < N; ++i) delete ptrs[i];
    delete[] ptrs;
}

If the goal is a single contiguous dynamic array of ints, prefer a signature that takes int* (or better, std::vector<int>&). As suggested, a contiguous block is simpler and safer:

void use_contig(std::vector<int>& v) {
    for (auto &x : v) x += 1;
}

int main() {
    std::vector<int> v(5);
    use_contig(v);
}

If the function must allocate memory for the caller, either return the pointer or accept a reference to the pointer (int*&) — that avoids assigning the address of a local. Summary: pick the right model (array-of-pointers vs contiguous block vs factory function), manage ownership explicitly, and avoid using addresses of local variables.

Recommended Answers

All 2 Replies

Just make sure you match the expected type. In this case, int *a[] is equivalent to int **a , so I would expect the function to be called something like this:

int main()
{
  int **a;

  // ...

  fctn ( a, SIZE );
}
int main()
{
    int* a = new int[2];
    func(a);
    delete[] a;
}

void func( int* a )
{
    // Do something with a
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.