"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Return an Array from a Function in C++?

How to Return an Array from a Function in C++?

Published on 2024-12-22
Browse:251

How to Return an Array from a Function in C  ?

Returning Arrays from a Function in C

You can return an array from a function in C by using pointers. However, this can lead to issues if the array is not properly allocated.

In your example, you are attempting to return an array that is allocated on the stack. This can cause undefined behavior when the function returns.

To avoid this issue, you can allocate the array on the heap using the new operator. You can then return a pointer to the allocated array.

int* uni(int *a, int *b) {
    int *c = new int[10];
    int i = 0;
    while (a[i] != -1) {
        c[i] = a[i];
        i  ;
    }
    for (; i 

You can then use the returned pointer to access the array.

int main() {
    int a[10] = {1, 3, 3, 8, 4, -1, -1, -1, -1, -1};
    int b[5] = {1, 3, 4, 3, 0};
    int *c = uni(a, b);
    for (int i = 0; i 

This will output:

1 3 3 8 4 1 3 4 3 0

Another alternative is to use a struct to wrap the array. This can be returned by value, and the struct will be copied, including the array that is internal within it.

struct myArray {
    int array[10];
};

myArray uni(int *a, int *b) {
    myArray c;
    int i = 0;
    while (a[i] != -1) {
        c.array[i] = a[i];
        i  ;
    }
    for (; i 

This will also output:

1 3 3 8 4 1 3 4 3 0
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3