Home > Backend Development > C++ > How do you safely return an array from a function in C ?

How do you safely return an array from a function in C ?

Linda Hamilton
Release: 2024-10-30 08:16:02
Original
257 people have browsed it

How do you safely return an array from a function in C  ?

Returning Arrays from Functions in C

In C , returning an array from a function can be a potential source of errors, especially if the array is allocated on the stack.

Consider the following code:

<code class="cpp">#include <iostream>

using namespace std;

int* uni(int *a, int *b) {
    int c[10];
    int i = 0;
    while (a[i] != -1) {
        c[i] = a[i];
        i++;
    }
    for (; i < 10; i++)
        c[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};
    int *c = uni(a, b);
    for (int i = 0; i < 10; i++)
        cout << c[i] << " ";
    cout << "\n";

    return 0;
}</code>
Copy after login

In this code, the uni() function creates an array c and merges the non-negative numbers from arrays a and b into c. However, when the code attempts to return c, the array goes out of scope, resulting in garbage values being returned.

To avoid this issue, it is typically recommended to pass arrays as pointers to functions and return the pointers. However, using pointers can be cumbersome, and in some cases, it can be preferable to use a different approach.

One alternative is to use a struct or class to encapsulate the array and return the object by value. Consider the following modified code:

<code class="cpp">#include <iostream>

using namespace std;

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>
Copy after login

In this example, the uni() function returns an instance of the myArray struct. The struct is returned by value, and its internal array is copied, ensuring that the values are valid even after the function returns.

The above is the detailed content of How do you safely return an array from a function in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template