Cpp function return array

Return Array from Functions in C++

C++ does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array’s name without an index.

If you want to return a single-dimension array from a function, you would have to declare a function returning a pointer as in the following example −

Second point to remember is that C++ does not advocate to return the address of a local variable to outside of the function so you would have to define the local variable as static variable.

Now, consider the following function, which will generate 10 random numbers and return them using an array and call this function as follows −

#include #include using namespace std; // function to generate and retrun random numbers. int * getRandom( ) < static int r[10]; // set the seed srand( (unsigned)time( NULL ) ); for (int i = 0; i < 10; ++i) < r[i] = rand(); cout return r; > // main function to call above defined function. int main () < // a pointer to an int. int *p; p = getRandom(); for ( int i = 0; i < 10; i++ ) < cout return 0; >

When the above code is compiled together and executed, it produces result something as follows −

624723190 1468735695 807113585 976495677 613357504 1377296355 1530315259 1778906708 1820354158 667126415 *(p + 0) : 624723190 *(p + 1) : 1468735695 *(p + 2) : 807113585 *(p + 3) : 976495677 *(p + 4) : 613357504 *(p + 5) : 1377296355 *(p + 6) : 1530315259 *(p + 7) : 1778906708 *(p + 8) : 1820354158 *(p + 9) : 667126415

Источник

Читайте также:  Python connect to linux server

Return Array From Function C++

Arrays store the data of the same type in a consecutive memory location. Functions break the bigger problems into smaller chunks to make it easier for programmers to code. Another advantage of using the function is that it makes the code look presentable and clean. Sometimes, we need a function that returns an array so that we can utilize that array in other functions. Then, comes the concept of the array return function in C++. It is the function that returns the array to another function. In this Linux Hint tutorial we will show you with examples how to return arrays from functions that you write in the C++ language.

Methods:

To return a complete array on a single function call is not possible. We do this with different techniques. There are three methodologies in C++ to return an array from a function. We will explain all of them one after another with codes.

Return the array from a function using:

Pointers in any programming language are used to hold the memory address of another memory location in it. Pointers are also used to pass one function to another function. With this, we can pass an array data to the other functions.

In pointers, there are also two approaches to return the array from a function:

The structures are utilized to store the different data types in it. Inside the structures, we can store the array and make an instance of that structure. This way, we can return the array. We can make more than one instance of structure to access the array that is stored in the structure.

This is another function that is used to return the array from the function in C++. It also provides two methods – one is the size() and the other is empty(). The std::array, we can say, is a template of structures. But the two methods it provides are the plus point of using this function to get the array from any function. This function is rarely used; we often use pointers and structure.

Example 1:

Now, to explain how we can use the pointers to return the dynamic array from a function, look at the following code:

#include
using namespace std;
char * character_func ( )
{
char * array_0 = new char [ 3 ] ;
array_0 [ 0 ] = ‘a’ ;
array_0 [ 1 ] = ‘b’ ;
array_0 [ 2 ] = ‘c’ ;
return array_0;
}
int main ( )
{
char * p = character_func ( ) ;
cout cout return 0 ;
}

After declaring the library, define a character_func()function to store the array in it. The function is a return type function. The return type is “char” which returns the character array. Char* tells that it is a pointer to store the character type data. Inside this function, declare an array of the pointer to store the character array. The size of the array is 3. Then, the array is initialized by the index number and returns the array variable. We store the character array in “array_0”. In the main() method, create a pointer “p” of the character type and store the character_func() in it. This means, with the help of this pointer “p”, we can access the elements in character_func(). Then, show a message on the terminal with the “cout

Example 2:

Here, we utilize the pointers to return the static array from a function.

#include
using namespace std;
float * floating_func ( )
{
static float array_1 [ 2 ] ;
array_1 [ 0 ] = 3.5 ;
array_1 [ 1 ] = 5.7 ;
return array_1;
}
int main ( )
{
float * pointer = floating_func ( ) ;
cout cout return 0 ;
}

In this example, let’s take a return type pointer function of float type that returns the floating point array. Within the floating_func()function, initialize a floating point array – “array_1” – of size 2. Here, we use the keyword “static” to set the variable as a local variable that can be accessed outside the function. Now, declare the array and returns the array variable. In the main() function, define a floating point pointer and assign a floating_func() function to it. Then, represent a message on the screen. With the help of a pointer, we can now access all the elements of the return type function. Show the array elements by calling a pointer. The pointer goes inside the function and gets the array that we set as the return. Employ the “return 0” statement to terminate the code.

Example 3:

In this last instance, we return an array from a function using structures.

#include
using namespace std;
struct arr {
int a [ 5 ] ;
} ;
struct arr arr_func ( )
{
struct arr val;
val.a [ 0 ] = 5 ;
val.a [ 1 ] = 67 ;
val.a [ 2 ] = 98 ;
val.a [ 3 ] = 77 ;
val.a [ 4 ] = 55 ;
return val;
}
int main ( )
{
struct arr val = arr_func ( ) ;
cout for ( int i = 0 ; i < 5 ; i++ )
{
cout }
return 0 ;
}

Define the “arr” structure using the “struct” keyword. In this struct, initialize an array of size 5. Then, we declare the different variables and access them with the name of the structure to use them in the functions. Now, create a structure-function arr_func() to initialize the array. To do so, define a “struct” to call the “val” variable. The “val” variable accesses the location of the “struct” array and store the value in it. All the array items are now stored in “val”. In the main() method, create the instance of “struct” and assign the arr_func() function to it. Print “The array is” text on the console by calling the “cout

Conclusion

This article illustrates on how to return an array from a function in C++. The array can be returned from the function with three different approaches. Each methodology is explained in detail, following the coding example. Everything is addressed from the very beginning including the usage of pointers and their types, the use of structures, and the std::array function. C++ does not have built-in methods like the other languages provide, so we have to do everything on our own. C++ is best for beginners to understand the basics of coding.

About the author

Ann-ul Hayyat

I’m a professional SEO and technical content writer with extensive experience in these fields as well as writing content for blogs, websites, reports, and other topics related to education, science, sports, and many other areas. I am skilled and experienced in creating SEO-friendly blog posts, technical articles, and other content on themes that you may find interesting.

Источник

Return Array from Functions in C++

C++ does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array’s name without an index.

If you want to return a single-dimension array from a function, you would have to declare a function returning a pointer as in the following example −

Second point to remember is that C++ does not advocate to return the address of a local variable to outside of the function so you would have to define the local variable as static variable.

Now, consider the following function, which will generate 10 random numbers and return them using an array and call this function as follows −

#include #include using namespace std; // function to generate and retrun random numbers. int * getRandom( ) < static int r[10]; // set the seed srand( (unsigned)time( NULL ) ); for (int i = 0; i < 10; ++i) < r[i] = rand(); cout return r; > // main function to call above defined function. int main () < // a pointer to an int. int *p; p = getRandom(); for ( int i = 0; i < 10; i++ ) < cout return 0; >

When the above code is compiled together and executed, it produces result something as follows −

624723190 1468735695 807113585 976495677 613357504 1377296355 1530315259 1778906708 1820354158 667126415 *(p + 0) : 624723190 *(p + 1) : 1468735695 *(p + 2) : 807113585 *(p + 3) : 976495677 *(p + 4) : 613357504 *(p + 5) : 1377296355 *(p + 6) : 1530315259 *(p + 7) : 1778906708 *(p + 8) : 1820354158 *(p + 9) : 667126415

Источник

How to return an Array from a function in C++

This tutorial will discuss about a unique way to return an array from a function in C++.

We can return only a single value from a function. But to return an array from a function, we need to return two values i.e.

We can create a pair of int pointer and size_t to store this information, and return that pair from the function. The one who is calling the function can fetch the integer pointer and size of array from the pair and use them to access array elements.

Let’s see a function that creates an int array on heap, and initializes that array with incemental values. Then it creates a pair of,

// Creates an int array of size 10 dynamically // and returns a pair of int * , & size of array std::pair getData() < size_t len = 10; // Create a dynamic int array of size 10 int* arr = new int[len]; // Initialize the value sof array for (int i = 0; i < len; i++) < arr[i] = i; >// Return a pair of an int pointer pointing to array // and size of array return std::make_pair(arr, len); >

We need to include the header file to use the std::pair and std::make_pair() . Then we can call this function to get the array details from the returned pair,

Frequently Asked:

// Get an array from a function std::pair result = getData(); // Fetch first element of pair i.e. int pointer int * arr = result.first; // Fetch second element of pair i.e. size size_t len = result.second;

Let’s see the complete example, where will fetch an array from a function and the interate over that array to print its contents.

Let’s see the complete example,

Are you a C++ programmer eager to step up your game?

Master the intricacies of C++/C++11/C++20 with our handpicked list of the Best Courses to Learn Modern C++11, C++17 and C++20. Sharpen your skills, conquer complex algorithms, and stand out in your professional or academic sphere.

This isn’t just about learning — it’s about transforming into the programmer you aspire to be. So, why wait?

Your leap towards programming excellence is just a click away.

#include #include // Creates an int array of size 10 dynamically // and returns a pair of int * , & size of array std::pair getData() < size_t len = 10; // Create a dynamic int array of size 10 int* arr = new int[len]; // Initialize the value sof array for (int i = 0; i < len; i++) < arr[i] = i; >// Return a pair of an int pointer pointing to array // and size of array return std::make_pair(arr, len); > int main() < // Get an array from a function std::pairresult = getData(); // Fetch first element of pair i.e. int pointer int * arr = result.first; // Fetch second element of pair i.e. size size_t len = result.second; // Iterate over array and print its contents for (int i = 0; i < len; i++) < std::coutstd::cout 

Summary

Today we learned about several ways to how to return an array from a function in C++. Thanks.

Share your love

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Terms of Use

Disclaimer

Copyright © 2023 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

Оцените статью