Home >Backend Development >C++ >How to Return an Array from a Function in C ?

How to Return an Array from a Function in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-29 08:05:30535browse

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.

<code class="C++">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 < 10; i++) {
        c[i] = b[i - 5];
    }
    return c;
}</code>

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

<code class="C++">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 < 10; i++) {
        cout << c[i] << " ";
    }
    cout << "\n";
    delete[] c;
    return 0;
}</code>

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.

<code class="C++">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 < 10; i++) {
        c.array[i] = b[i - 5];
    }
    return c;
}

int main() {
    int a[10] = {1, 3, 3, 8, 4, -1, -1, -1, -1, -1};
    int b[5] = {1, 3, 4, 3, 0};
    myArray c = uni(a, b);
    for (int i = 0; i < 10; i++) {
        cout << c.array[i] << " ";
    }
    cout << "\n";
    return 0;
}</code>

This will also output:

1 3 3 8 4 1 3 4 3 0

The above is the detailed content of How to Return an Array from a Function in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn