Will the array be deallocated and if so, what is a workaround?
double * GetArrayFromVector( std::map<std::string, double> m, char ** names, int count )
{
if(!names) return 0;
std::vector<double> vec(m.size());
for (int i=0; i<count; ++i)
{
if(!names[i]) return 0;
std::map<std::string, double>::iterator iter=m.find(name[i]);
if(iter!=m.end())
vec.push_back(iter->second);
else
return 0;
}
return &vec[0];
}
Thanks a lot
Divide your function on two.
Make your functions make just one action:
1. fill vector from map.
2. create array from vector.
Don't forget to pass map by const reference.
Main note: caller of the GetArrayFromVector is responsible for memory deallocation.
void FillVector( const std::map<std::string, double>& m,
std::vector< double >& v,
char ** names,
int count )
{
.......
}
double* createArray( const std::vector< double >& v )
{
double* result = new double [v.size()];
memcpy( result, &v.front(), v.size() * sizeof( double ) );
return result;
}
// and finally your function
double* GetArrayFromVector( const std::map<std::string, double>& m,
char ** names,
int count )
{
std::vector< double > v;
FillVector( m, v, names, count );
return CreateArray( v );
}
Yes -- it's deallocated as soon as your return from the function, because vec is declared on the stack. The std::vector destructor takes care of freeing the memory. Since you're returning the address of a deallocated array, you're going to start messing around with deallocated memory, which is a big no-no. At best, you'll crash immediately. At worst, you'll silently succeed with a big gaping security hole.
There are two ways to fix this: (1) return the entire vector by-value, which makes a copy of the entire vector, or (2) return the vector via a reference parameter.
Solution 1:
std::vector<double> GetArrayFromVector(...)
{
...
return vec; // make copy of entire vec, probably not a good idea
}
Solution 2:
void GetArrayFromVector(..., std::vector<double> & vec)
{
// compute result, store it in vec
}
Yes the array will be deallocated.
Change the function to:
double * GetArrayFromVector( std::map<std::string, double> m, vector<double> &vec, char ** names, int count )
{
vec.clear();
vec.reserve(m.size());
for (int i=0; i<count; ++i)
{
if(!names[i]) return 0;
std::map<std::string, double>::iterator iter=m.find(name[i]);
if(iter!=m.end())
vec.push_back(iter->second);
else
return 0;
}
return &vec[0];
}
Or else use boost::shared_array (also, look at boost::scoped_array)
boost::shared_array<double> GetArrayFromVector( std::map<std::string, double> m, char ** names, int count )
{
boost::shared_array<double> vec(new double[m.size()]);
for (int i=0; i<count; ++i)
{
if(!names[i]) return boost::shared_array<double>();
std::map<std::string, double>::iterator iter=m.find(name[i]);
if(iter!=m.end())
vec[i] = iter->second;
else
return boost::shared_array<double>();
}
return vec;
}
vec is a local variable. Its scope is limited to the GetArrayFromVector() function only. Never return the address of a local variable. Either return the array by value:
std::vector<double> GetArrayFromVector( std::map<std::string, double> m,
char ** names, int count )
or, pass a reference to the vector as an output parameter:
void GetArrayFromVector( std::map<std::string, double> m,
char ** names, int count,
std::vector<double>& vec)
or, pass an output iterator:
void GetArrayFromVector( std::map<std::string, double> m,
char ** names, int count,
std::vector<double>::iterator vecIter)
The last two will require some careful implementation of the function definition and calling though.
Additionally, if you are game for a bit more adventure try this:
// you'd need to change the value to use when an element is not
// found in the map to something that suits your needs
double pred(std::map<char*, double> haystick, char* const needle) {
std::map<char*, double>::iterator i = haystick.find(needle);
return i != haystick.end() ? i->second : 0;
}
int main(int argc, char* argv[])
{
std::map<char *, double> m;
std::vector<char *> names;
std::vector<double> dv;
m[ "Sasha" ] = 729.0;
m[ "josh" ] = 8154.0;
names.push_back("Sasha");
names.push_back("JonSkeet");
names.push_back("josh");
// transform is part of STL's <algorithm> header
// it takes a container (actually a range -- [begin(), end())
// note it is a half-open range -----------^
// as is customary for all STL algorithms, applies the function
// or functor specified as the last parameter to each element of
// the sequence and writes the result back to another container
// specified via the output iterator -- the third argument
//
// since I have not reserved enough elements for the vector dv
// i cannot blindly use it -- i need a back_inserter to coax
// transform to push_back() instead of do an insert operation
// of course, for vectors, this is costly since reallocations
// may happen, but let's leave the performance aside for a while!
//
// ok, so what about the last parameter, you ask? it has to be an
// unary_operation. well, mostly so. but what is it that we want?
// we want to take an iterator from the original char* (string)
// array and see if there's an entry in the map. if there is one
// we retrieve the associated double value and put it in dv; else,
// we set a default value of 0 -- change it to whatever pleases you
// maybe a std::numeric_limit<double> if it works for you.
//
// you can create a functor inheriting std::unary_function and pass
// it on. that's the easy way out. but what if you already have a
// comparator, a C-style find() function? will it work? yes, it will.
// but we have to wrap it using the function adaptor std::ptr_fun
// to make the compiler happy (after all it wants a unary_function, right?)
//
// this simple scheme of things works very well, save for a last little
// glitch. the comparator actually takes two parameters -- a what to search
// and a where to search. and guess what -- the where to search is always
// fixed. so that gives us a good oppertunity to fix the first parameter to
// our map<char*, double> which is exactly what std::bind1st() does.
// surprisingly, now that you've fixed one function, you no longer have a
// binary function (one taking two arguments) but an unary one -- which is
// just what you'd pass to transform. voila!
std::transform(names.begin(), names.end(), std::back_inserter(dv),
std::bind1st(std::ptr_fun(pred), m));
std::copy(dv.begin(), dv.end(),
std::ostream_iterator<double>(std::cout, "\n"));
return 0;
}
Some interesting links:
transform [actually, comes in two flavors]
bind1st or binder1st [there's a binder2nd too!]
back_inserter
ptr_fun [check out mem_fun also]
unary_function [and there's binary_function]
Also check out Boost. They have done some magic with bind()!
You can pass it by reference or new/delete it, but as posted your vector will be destructed after the function returns.
Yes, the vector (and the data store it holds) will be deallocated when the function ends.
Why are you creating a vector? If you want an array, just create & fill one of those..
double * GetArrayFromVector( std::map<std::string, double> m, char * names[], int count )
{
if(!names) return 0;
double* vec = new double[m.size()];
int j = 0;
for (int i=0; i<count; ++i)
{
if(!names[i]) return 0;
std::map<std::string, double>::iterator iter=m.find(name[i]);
if(iter!=m.end())
vec[j++] =iter->second;
else
return 0;
}
return vec;
}
Yes the vector will be deallocated when the function exits (and the 'vec' variable goes out of scope). The pointer you return will therefore be invalid.
An alternative is to allocate the array on the heap (using the 'new' operator) and return that pointer instead, but it will be the caller's responsibility to 'delete' the pointer, which is usually frown upon.
A better alternative is to return a shared_ptr to your array.
Since you know count up front, there's no benefit to using an stl vector. You could simply do this:
double* GetArrayFromVector(std::map<char*, double> m, char** names, int count)
{
double* result = new double[count];
for (int i = 0; i < count; ++i)
{
if(!names[i])
{
delete[] result;
return 0;
}
map<std::string, double>::iterator iter = m.find(name[i]);
if(iter != m.end())
{
result[i] = iter->second;
}
else
{
delete[] result;
return 0;
}
}
return result;
}
Note that you are passing ownership of the allocated array to the caller. Personally, I'd try to write the code in a way that observes the RAII principle; either pass in a vector to be populated, or use a managed/shared pointer, etc. (both of these options have been suggested in other answers).
There is a concept call move constructors that would allow you to transfer the ownership of a resource held by a (stack-based) object to a new object. I have heard that STLport has a move_source template to accomplish this
This will be coming to C++0x.
In this case, you would be returning std::vector<double> instead of double*.
Kinda surprised no one has mentioned vector::swap. Have the caller pass in a reference to a vector which will have its contents replaced by the function:
void GetArrayFromVector( std::vector<double>& output, ... )
{
std::vector<double> vec(m.size());
// construct vec here...
output.swap(vec);
}
BTW: "GetArrayFromVector" and you pass in a map?
You could use std::auto_ptr smart pointer (but passing vector reference to your function is better solution).
Example of std::auto_ptr:
std::auto_ptr< std::vector<int> > getArray(int& count){
std::auto_ptr< std::vector<int> > vec(new std::vector<int>());
vec->push_back(10);
vec->push_back(12);
vec->push_back(14);
vec->push_back(16);
count = vec->size();
return vec;
}
int main(){
int size = 0;
std::auto_ptr< std::vector<int> > autoPtrVec = getArray(size);
int* ptr = &(*autoPtrVec)[0];
std::cout << "Size: " << size << std::endl;
for(int i=0; i<size; i++){
std::cout << "[" << i << "]=" << ptr[i] << std::endl;
}
return 0;
}
C++ vectors have a data() method which returns a pointer to the underlying array.
// vector::data
#include <iostream>
#include <vector>
int main ()
{
std::vector<int> myvector (5);
int* p = myvector.data();
*p = 10;
++p;
*p = 20;
p[2] = 100;
std::cout << "myvector contains:";
for (unsigned i=0; i<myvector.size(); ++i)
std::cout << ' ' << myvector[i];
std::cout << '\n';
return 0;
}
which outputs
myvector contains: 10 20 0 100 0
Related
I have a function myfun which will return a vector.
vector<double> myfun(const size_t k, const size_t i){
vector<double> v(k);
// do some computation with remaining arguments
return v;
}
Then, I will use it in the loop to update v and use v to get some result.
int main(){
size_t N = 100; // iteration size
size_t n = 10; // size of v
vector<double> result(N);
vector<double> v(n);
for(size_t i = 0; i<N; i++){
v = myfun(n,i); // compute for each iteration
result[i] = compute_some_value(v);
}
}
So, my question is:
Does v actually allocated inside of myfun every time it is called?
If it does, what happens to old v?
Also, is it better to use just use address like void myfun(some_args, vector<double> &v) for output argument v?
Does v actually allocated inside of myfun every time it is called?
Yes
If it does, what happens to old v?
It gets overwritten.
Also, is it better to use just use address like void myfun(some_args, vector &v) for output argument v?
Yes, it's better to pass vector by reference depending on your operations.
You could do it this way
double compute_some_value(vector<double> & v, const size_t i) {
v.clear(); // use if required
// do some computation with remaining arguments and return
}
int main() {
size_t N = 100; // iteration size
size_t n = 10; // size of v
vector<double> result(N), v(n);
for (size_t i = 0; i < N; i++) {
result[i] = compute_some_value(v, i);
}
}
Does v actually allocated inside of myfun every time it is called?
Yes
If it does, what happens to old v?
When v gets out of scope the destructor is called and the object gets destruct. This is why you don't really have to call destructor of a class explicitly.
Also, is it better to use just use address like void myfun(some_args,
vector &v) for output argument v?
It really depends on your use case. If it concerns with memory issues, its better to pass the reference.
I have an array int arr[5] that is passed to a function fillarr(int arr[]):
int fillarr(int arr[])
{
for(...);
return arr;
}
How can I return that array?
How will I use it, say I returned a pointer how am I going to access it?
In this case, your array variable arr can actually also be treated as a pointer to the beginning of your array's block in memory, by an implicit conversion. This syntax that you're using:
int fillarr(int arr[])
Is kind of just syntactic sugar. You could really replace it with this and it would still work:
int fillarr(int* arr)
So in the same sense, what you want to return from your function is actually a pointer to the first element in the array:
int* fillarr(int arr[])
And you'll still be able to use it just like you would a normal array:
int main()
{
int y[10];
int *a = fillarr(y);
cout << a[0] << endl;
}
C++ functions can't return C-style arrays by value. The closest thing is to return a pointer. Furthermore, an array type in the argument list is simply converted to a pointer.
int *fillarr( int arr[] ) { // arr "decays" to type int *
return arr;
}
You can improve it by using an array references for the argument and return, which prevents the decay:
int ( &fillarr( int (&arr)[5] ) )[5] { // no decay; argument must be size 5
return arr;
}
With Boost or C++11, pass-by-reference is only optional and the syntax is less mind-bending:
array< int, 5 > &fillarr( array< int, 5 > &arr ) {
return arr; // "array" being boost::array or std::array
}
The array template simply generates a struct containing a C-style array, so you can apply object-oriented semantics yet retain the array's original simplicity.
In C++11, you can return std::array.
#include <array>
using namespace std;
array<int, 5> fillarr(int arr[])
{
array<int, 5> arr2;
for(int i=0; i<5; ++i) {
arr2[i]=arr[i]*2;
}
return arr2;
}
$8.3.5/8 states-
"Functions shall not have a return type of type array or function, although they may have a return type of type pointer or reference to such things. There shall be no arrays of functions, although there can be arrays of pointers to functions."
int (&fn1(int (&arr)[5]))[5]{ // declare fn1 as returning refernce to array
return arr;
}
int *fn2(int arr[]){ // declare fn2 as returning pointer to array
return arr;
}
int main(){
int buf[5];
fn1(buf);
fn2(buf);
}
the answer may depend a bit on how you plan to use that function. For the simplest answer, lets decide that instead of an array, what you really want is a vector. Vectors are nice because the look for all the world like boring, ordinary values you can store in regular pointers. We'll look at other options and why you want them afterwards:
std::vector<int> fillarr( std::vector<int> arr ) {
// do something
return arr;
}
This will do exactly what you expect it to do. The upside is that std::vector takes care of making sure everything is handled cleanly. the downside is that this copies a very large amount of data, if your array is large. In fact it copies every element of the array twice. first it copies the vector so that the function can use it as a parameter. then it copies it again to return it to the caller. If you can handle managing the vector yourself, you can do things quite a bit more easily. (it may copy it a third time if the caller needs to store it in a variable of some sort to do more calculation)
It looks like what you're really trying to do is just populate a collection. if you don't have a specific reason to return a new instance of a collection, then don't. we can do it like this
void fillarr(std::vector<int> & arr) {
// modify arr
// don't return anything
}
this way you get a reference to the array passed to the function, not a private copy of it. any changes you make to the parameter are seen by the caller. You could return a reference to it if you want, but that's not really a great idea, since it sort of implies that you're getting something different from what you passed.
If you really do need a new instance of the collection, but want to avoid having it on the stack (and all the copying that entails), you need to create some kind of contract for how that instance is handled. the easiest way to do that is to use a smart pointer, which keeps the referenced instance around as long as anyone is holding onto it. It goes away cleanly if it goes out of scope. That would look like this.
std::auto_ptr<std::vector<int> > fillarr( const std::vector<int> & arr) {
std::auto_ptr<std::vector<int> > myArr(new std::vector<int>);
// do stuff with arr and *myArr
return myArr;
}
For the most part, using *myArr works identically to using a plain vanilla vector. This example also modifies the parameter list by adding the const keyword. Now you get a reference without copying it, but you can't modify it, so the caller knows it'll be the same as before the function got to it.
All of this is swell, but idiomatic c++ rarely works with collections as a whole. More normally, you will be using iterators over those collections. that would look something more like this
template <class Iterator>
Iterator fillarr(Iterator arrStart, Iterator arrEnd) {
Iterator arrIter = arrStart;
for(;arrIter <= arrEnd; arrIter++)
;// do something
return arrStart;
}
Using it looks a bit odd if you're not used to seeing this style.
vector<int> arr;
vector<int>::iterator foo = fillarr(arr.begin(), arr.end());
foo now 'points to' the beginning of the modified arr.
What's really nice about this is that it works equally well on vector as on plain C arrays and many other types of collection, for example
int arr[100];
int *foo = fillarr(arr, arr+100);
Which now looks an awful lot like the plain pointer examples given elsewhere in this question.
This:
int fillarr(int arr[])
is actually treated the same as:
int fillarr(int *arr)
Now if you really want to return an array you can change that line to
int * fillarr(int arr[]){
// do something to arr
return arr;
}
It's not really returning an array. you're returning a pointer to the start of the
array address.
But remember when you pass in the array, you're only passing in a pointer.
So when you modify the array data, you're actually modifying the data that the
pointer is pointing at. Therefore before you passed in the array, you must realise
that you already have on the outside the modified result.
e.g.
int fillarr(int arr[]){
array[0] = 10;
array[1] = 5;
}
int main(int argc, char* argv[]){
int arr[] = { 1,2,3,4,5 };
// arr[0] == 1
// arr[1] == 2 etc
int result = fillarr(arr);
// arr[0] == 10
// arr[1] == 5
return 0;
}
I suggest you might want to consider putting a length into your fillarr function like
this.
int * fillarr(int arr[], int length)
That way you can use length to fill the array to it's length no matter what it is.
To actually use it properly. Do something like this:
int * fillarr(int arr[], int length){
for (int i = 0; i < length; ++i){
// arr[i] = ? // do what you want to do here
}
return arr;
}
// then where you want to use it.
int arr[5];
int *arr2;
arr2 = fillarr(arr, 5);
// at this point, arr & arr2 are basically the same, just slightly
// different types. You can cast arr to a (char*) and it'll be the same.
If all you're wanting to do is set the array to some default values, consider using
the built in memset function.
something like:
memset((int*)&arr, 5, sizeof(int));
While I'm on the topic though. You say you're using C++. Have a look at using stl vectors. Your code is likely to be more robust.
There are lots of tutorials. Here is one that gives you an idea of how to use them.
http://www.yolinux.com/TUTORIALS/LinuxTutorialC++STL.html
This is a fairly old question, but I'm going to put in my 2 cents as there are a lot of answers, but none showing all possible methods in a clear and concise manner (not sure about the concise bit, as this got a bit out of hand. TL;DR 😉).
I'm assuming that the OP wanted to return the array that was passed in without copying as some means of directly passing this to the caller to be passed to another function to make the code look prettier.
However, to use an array like this is to let it decay into a pointer and have the compiler treat it like an array. This can result in subtle bugs if you pass in an array like, with the function expecting that it will have 5 elements, but your caller actually passes in some other number.
There a few ways you can handle this better. Pass in a std::vector or std::array (not sure if std::array was around in 2010 when the question was asked). You can then pass the object as a reference without any copying/moving of the object.
std::array<int, 5>& fillarr(std::array<int, 5>& arr)
{
// (before c++11)
for(auto it = arr.begin(); it != arr.end(); ++it)
{ /* do stuff */ }
// Note the following are for c++11 and higher. They will work for all
// the other examples below except for the stuff after the Edit.
// (c++11 and up)
for(auto it = std::begin(arr); it != std::end(arr); ++it)
{ /* do stuff */ }
// range for loop (c++11 and up)
for(auto& element : arr)
{ /* do stuff */ }
return arr;
}
std::vector<int>& fillarr(std::vector<int>& arr)
{
for(auto it = arr.begin(); it != arr.end(); ++it)
{ /* do stuff */ }
return arr;
}
However, if you insist on playing with C arrays, then use a template which will keep the information of how many items in the array.
template <size_t N>
int(&fillarr(int(&arr)[N]))[N]
{
// N is easier and cleaner than specifying sizeof(arr)/sizeof(arr[0])
for(int* it = arr; it != arr + N; ++it)
{ /* do stuff */ }
return arr;
}
Except, that looks butt ugly, and super hard to read. I now use something to help with that which wasn't around in 2010, which I also use for function pointers:
template <typename T>
using type_t = T;
template <size_t N>
type_t<int(&)[N]> fillarr(type_t<int(&)[N]> arr)
{
// N is easier and cleaner than specifying sizeof(arr)/sizeof(arr[0])
for(int* it = arr; it != arr + N; ++it)
{ /* do stuff */ }
return arr;
}
This moves the type where one would expect it to be, making this far more readable. Of course, using a template is superfluous if you are not going to use anything but 5 elements, so you can of course hard code it:
type_t<int(&)[5]> fillarr(type_t<int(&)[5]> arr)
{
// Prefer using the compiler to figure out how many elements there are
// as it reduces the number of locations where you have to change if needed.
for(int* it = arr; it != arr + sizeof(arr)/sizeof(arr[0]); ++it)
{ /* do stuff */ }
return arr;
}
As I said, my type_t<> trick wouldn't have worked at the time this question was asked. The best you could have hoped for back then was to use a type in a struct:
template<typename T>
struct type
{
typedef T type;
};
typename type<int(&)[5]>::type fillarr(typename type<int(&)[5]>::type arr)
{
// Prefer using the compiler to figure out how many elements there are
// as it reduces the number of locations where you have to change if needed.
for(int* it = arr; it != arr + sizeof(arr)/sizeof(arr[0]); ++it)
{ /* do stuff */ }
return arr;
}
Which starts to look pretty ugly again, but at least is still more readable, though the typename may have been optional back then depending on the compiler, resulting in:
type<int(&)[5]>::type fillarr(type<int(&)[5]>::type arr)
{
// Prefer using the compiler to figure out how many elements there are
// as it reduces the number of locations where you have to change if needed.
for(int* it = arr; it != arr + sizeof(arr)/sizeof(arr[0]); ++it)
{ /* do stuff */ }
return arr;
}
And then of course you could have specified a specific type, rather than using my helper.
typedef int(&array5)[5];
array5 fillarr(array5 arr)
{
// Prefer using the compiler to figure out how many elements there are
// as it reduces the number of locations where you have to change if needed.
for(int* it = arr; it != arr + sizeof(arr)/sizeof(arr[0]); ++it)
{ /* do stuff */ }
return arr;
}
Back then, the free functions std::begin() and std::end() didn't exist, though could have been easily implemented. This would have allowed iterating over the array in a safer manner as they make sense on a C array, but not a pointer.
As for accessing the array, you could either pass it to another function that takes the same parameter type, or make an alias to it (which wouldn't make much sense as you already have the original in that scope). Accessing a array reference is just like accessing the original array.
void other_function(type_t<int(&)[5]> x) { /* do something else */ }
void fn()
{
int array[5];
other_function(fillarr(array));
}
or
void fn()
{
int array[5];
auto& array2 = fillarr(array); // alias. But why bother.
int forth_entry = array[4];
int forth_entry2 = array2[4]; // same value as forth_entry
}
To summarize, it is best to not allow an array decay into a pointer if you intend to iterate over it. It is just a bad idea as it keeps the compiler from protecting you from shooting yourself in the foot and makes your code harder to read. Always try and help the compiler help you by keeping the types as long as possible unless you have a very good reason not to do so.
Edit
Oh, and for completeness, you can allow it to degrade to a pointer, but this decouples the array from the number of elements it holds. This is done a lot in C/C++ and is usually mitigated by passing the number of elements in the array. However, the compiler can't help you if you make a mistake and pass in the wrong value to the number of elements.
// separate size value
int* fillarr(int* arr, size_t size)
{
for(int* it = arr; it != arr + size; ++it)
{ /* do stuff */ }
return arr;
}
Instead of passing the size, you can pass the end pointer, which will point to one past the end of your array. This is useful as it makes for something that is closer to the std algorithms, which take a begin and and end pointer, but what you return is now only something that you must remember.
// separate end pointer
int* fillarr(int* arr, int* end)
{
for(int* it = arr; it != end; ++it)
{ /* do stuff */ }
return arr;
}
Alternatively, you can document that this function will only take 5 elements and hope that the user of your function doesn't do anything stupid.
// I document that this function will ONLY take 5 elements and
// return the same array of 5 elements. If you pass in anything
// else, may nazal demons exit thine nose!
int* fillarr(int* arr)
{
for(int* it = arr; it != arr + 5; ++it)
{ /* do stuff */ }
return arr;
}
Note that the return value has lost it's original type and is degraded to a pointer. Because of this, you are now on your own to ensure that you are not going to overrun the array.
You could pass a std::pair<int*, int*>, which you can use for begin and end and pass that around, but then it really stops looking like an array.
std::pair<int*, int*> fillarr(std::pair<int*, int*> arr)
{
for(int* it = arr.first; it != arr.second; ++it)
{ /* do stuff */ }
return arr; // if you change arr, then return the original arr value.
}
void fn()
{
int array[5];
auto array2 = fillarr(std::make_pair(&array[0], &array[5]));
// Can be done, but you have the original array in scope, so why bother.
int fourth_element = array2.first[4];
}
or
void other_function(std::pair<int*, int*> array)
{
// Can be done, but you have the original array in scope, so why bother.
int fourth_element = array2.first[4];
}
void fn()
{
int array[5];
other_function(fillarr(std::make_pair(&array[0], &array[5])));
}
Funny enough, this is very similar to how std::initializer_list work (c++11), but they don't work in this context.
to return an array from a function , let us define that array in a structure;
So it looks something like this
struct Marks{
int list[5];
}
Now let us create variables of the type structure.
typedef struct Marks marks;
marks marks_list;
We can pass array to a function in the following way and assign value to it:
void setMarks(int marks_array[]){
for(int i=0;i<sizeof(marks_array)/sizeof(int);i++)
marks_list.list[i]=marks_array[i];
}
We can also return the array. To return the array , the return type of the function should be of structure type ie marks. This is because in reality we are passing the structure that contains the array. So the final code may look like this.
marks getMarks(){
return marks_list;
}
the Simplest way to do this ,is to return it by reference , even if you don't write
the '&' symbol , it is automatically returned by reference
void fillarr(int arr[5])
{
for(...);
}
int *fillarr(int arr[])
You can still use the result like
int *returned_array = fillarr(some_other_array);
if(returned_array[0] == 3)
do_important_cool_stuff();
As above mentioned paths are correct. But i think if we just return a local array variable of a function sometimes it returns garbage values as its elements.
in-order to avoid that i had to create the array dynamically and proceed. Which is something like this.
int* func()
{
int* Arr = new int[100];
return Arr;
}
int main()
{
int* ArrResult = func();
cout << ArrResult[0] << " " << ArrResult[1] << endl;
return 0;
}
Source: https://www.tutorialspoint.com/cplusplus/cpp_return_arrays_from_functions.htm
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:
int * myFunction() {
.
.
.
}
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.
Applying these rules on the current question, we can write the program as follows:
# include <iostream>
using namespace std;
int * fillarr( );
int main ()
{
int *p;
p = fillarr();
for ( int i = 0; i < 5; i++ )
cout << "p[" << i << "] : "<< *(p + i) << endl;
return 0;
}
int * fillarr( )
{
static int arr[5];
for (int i = 0; i < 5; ++i)
arr[i] = i;
return arr;
}
The Output will be:
p[0]=0
p[1]=1
p[2]=2
p[3]=3
p[4]=4
template<typename T, size_t N>
using ARR_REF = T (&)[N];
template <typename T, size_t N>
ARR_REF<T,N> ArraySizeHelper(ARR_REF<T,N> arr);
#define arraysize(arr) sizeof(ArraySizeHelper(arr))
and what about:
int (*func())
{
int *f = new int[10] {1,2,3};
return f;
}
int fa[10] = { 0 };
auto func2() -> int (*) [10]
{
return &fa;
}
Actually when you pass an array inside a function, the pointer to the original array is passed in the function parameter and thus the changes made to the array inside that function is actually made on the original array.
#include <iostream>
using namespace std;
int* func(int ar[])
{
for(int i=0;i<100;i++)
ar[i]=i;
int *ptr=ar;
return ptr;
}
int main() {
int *p;
int y[100]={0};
p=func(y);
for(int i=0;i<100;i++)
cout<<i<<" : "<<y[i]<<'\n';
}
Run it and you will see the changes
And why don't "return" the array as a parameter?
fillarr(int source[], size_t dimSource, int dest[], size_t dimDest)
{
if (dimSource <= dimDest)
{
for (size_t i = 0; i < dimSource; i++)
{
//some stuff...
}
}
else
{
//some stuff..
}
}
or..in a simpler way (but you have to know the dimensions...):
fillarr(int source[], int dest[])
{
//...
}
A simple and elaborate example, so that I can refer here if I forget the concept and need help.
#include <iostream>
using namespace std;
int *ReturnArray(int arr[], int size)
{
static int MinMax[2] = {0, 0}; // must use static, else address would be deleted after the return is reached
MinMax[0] = arr[0];
MinMax[1] = arr[size - 1];
return MinMax;
}
int main()
{
int arr[] = {1, 2, 3};
int size = sizeof(arr) / sizeof(*arr);
int *ans; // pointer to hold returned array
ans = ReturnArray(arr, size); // only pointer can receive the return, not an array
cout << "Min: " << ans[0] << " Max: " << ans[1];
return 0;
}
Here's a full example of this kind of problem to solve
#include <bits/stdc++.h>
using namespace std;
int* solve(int brr[],int n)
{
sort(brr,brr+n);
return brr;
}
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
int *a=solve(arr,n);
for(int i=0;i<n;i++)
{
cout<<a[i]<<endl;
}
return 0;
}
i used static array so that while returning array it should not throw error as you are returning address of local variable...
so now you can send any locally created variable from function by making it as static...as it works as global variable....
#include<iostream>
using namespace std;
char *func(int n)
{
// char a[26]; /*if we use this then an error will occur because you are
// returning address of a local variable*/
static char a[26];
char temp='A';
for(int i=0;i<n;i++)
{
a[i]=temp;temp++;
}
return a;
}
int main()
{
int n=26;
char *p=func(n);
for(int i=0;i<n;i++)
cout<<*(p+i)<<" ";
//or you can also print like this
for(int i=0;i<n;i++)
cout<<p[i]<<" ";
}
Just define a type[ ] as return value, like:
private string[] functionReturnValueArray(string one, string two)
{
string[] x = {one, two};
x[0] = "a";
x[1] = "b";
return x;
}
.
.
.
function call:
string[] y;
y = functionReturnValueArray(stringOne, stringTwo)
I am trying to apply transform to a shared_ptr and store to a shared_ptr while also using a function in a class.
I created this example:
#include <vector>
#include <iostream>
#include <memory>
#include <algorithm>
using namespace std;
class MyClass {
public:
int factor = 0;
MyClass(const int factor_) : factor(factor_) {}
shared_ptr<vector<int> > mult(shared_ptr<vector<int> > numbers) {
shared_ptr<vector<int> > result(new vector<int>() );
transform(numbers->begin(), numbers->end(), result->begin(),
[this](int x){ return factor * x; });
return result;
}
};
int main()
{
shared_ptr<vector<int> > numbers(new vector<int>());
shared_ptr<vector<int> > res(new vector<int>());
MyClass times_two(2);
numbers->push_back(1);
numbers->push_back(2);
numbers->push_back(3);
res = times_two.mult(numbers);
cout << "{";
for (unsigned int i = 0; i < res->size(); ++i)
cout << res->at(i) << ", ";
cout << "}";
return 0;
}
As can be seen here this causes a segmentation dump. Any help on how I could resolve this so that the output yields {2, 4, 6, }?
Note that I use the lambda because I need it in my full implementation.
I tried also to replace,
transform(numbers->begin(), numbers->end(), result->begin(),
[this](int x){ return factor * x; });
with
transform((*numbers).begin(), (*numbers).end(), (*result).begin(),
[this](int x){ return factor * x; });
shared_ptr<vector<int> > result(new vector<int>() );
You construct a new, empty vector.
transform(numbers->begin(), numbers->end(), result->begin(),
[this](int x){ return factor * x; });
Since result is empty, result->begin() returns the ending iterator value. std::transform copies the input sequence, applies the transformation lambda, and writes the transformed result to the output iterator.
Since the vector is empty, there's nothing to write to. You're running past the end of the empty array, resulting in undefined behavior and memory corruption.
In this case, simply preallocate the output array, since you know what its size should be, in advance:
shared_ptr<vector<int> > result(new vector<int>(numbers->size()) );
Now, this will create the output array of the correct size, begin() will return an iterator to the beginning of the array, and std::transform() will happily scribble over the array.
If you really wish to avoid the extra overhead of value-initializing the new array, just to have it overwritten, you can use reserve() to preallocate the array's final size, then use a std::back_insert_iterator for the output iterator, instead of passing in begin().
Understanding std::set.insert & std::vector behavior.
Please consider the following scenario:
A.h
class A {
uint id;
vector<double> values;
operator<(const A& argA) const;
}
A.cpp
A::A(uint argId, vector<double> argValues) {
this->id = argId;
this->values = argValues;
}
A::operator<(const A& argA) const {
// it's guaranteed that there's always at least one element in the vector
return this->values[0] < argA.values[0];
}
B.cpp
std::set<A> mySet;
for (uint i = 0; i < (uint) 10; i++)
{
vector<double> tempVector(3);
for (uint j = 0; j < (uint) 3; j++) {
tempVector[j] = j;
}
myset.insert(A(i + 1, tempVector));
}
In my understanding, tempElement owns a deep copied vector (values), because the vector was passed by value in its constructor and assigned. Therefore looping over i shouldn't break the added elements to my set. BUT inserting *tempElement breaks - SIGSEV. In my logic this should work... Every help appreciated!
EDIT: the code crashes during the insertion process (second element); set invokes the LT-operator, tries to access the vector of the passed argument - but cannot. Before the creation of A where I pass the id and the vector I check if the passed vector contains the right elements.
For a small vector it shouldn't matter, but if you have a large array and it will be expensive to keep copying it, yourA should contain some kind of pointer that shallow-copies. There are several options:
boost::shared_array<double>
boost::shared_ptr<vector<double> >
boost::shared_ptr<double> but with array deleter passed in on construction.
Make A non-copyable and have a set of (shared) pointers to A with some comparison functor that compares what is in the pointers rather than the pointers themselves.
Note that with either shared_array or shared_ptr you won't be able to extract the size (number of elements) so you would have to store that separately.
I don't think the problem is in this code. However I notice you have a vector tempVector but you assing the values to tempComponents instead. I can't see tempComponents declaration but my guess is it is of different size.
Working code with numerous changes - but I don't see the problem that you were describing.
#include <set>
#include <vector>
using namespace std;
typedef unsigned int uint;
class A {
public:
A(uint argId, vector<double> argValues)
{
this->id = argId;
this->values = argValues;
}
bool operator < ( A const& a ) const
{
return a.id < id;
}
uint id;
vector<double> values;
};
int _tmain(int argc, _TCHAR* argv[])
{
std::set<A> mySet;
for (uint i = 0; i < (uint) 10; i++)
{
vector<double> tempVector(3);
for (uint j = 0; j < (uint) 3; j++) {
tempVector[j] = j;
}
std::unique_ptr<A> tempElement(new A(i + 1, tempVector));
mySet.insert(*tempElement);
}
return 0;
}
No, there's no reason for inserting into myset here to cause a crash. The problem must lie elsewhere. Perhaps in A's copy ctor if you're not using the default one.
However your code is leaking memory. When you insert into the set *tempElement is copied into the set, and then the original that you allocated with new is no longer used but is never deleted. Instead you could just do A tempElement(i+1,tempVector); so that after the object is copied into the set it gets properly destroyed. Or perhaps better in this case you could just construct it as a temporary passed directly to insert: myset.insert(A(i+1,tempVector)) in which case the object will be moved instead of copied, reducing the overhead. Or you could just construct the object in place to avoid even moving: myset.emplace(i+1,tempVector);
Also I'm assuming that by tempComponents[j] = j; you meant tempVector[j] = j. You could replace that loop with std::iota(begin(tempVector),end(tempVector),0). edit: or you could use the new initializer syntax Furthermore, since the vector is the same everytime you could use just one outside the loop:
vector<double> tempVector(3) = {0.0,1.0,2.0}
std::set<A> mySet;
for (uint i = 0; i < (uint) 10; i++)
{
myset.emplace(i+1,tempVector);
}
C++03 compilers won't support emplace or the new initializer syntax, and iota would be a compiler extension for them (it's from the original SGI STL, so some may have it). For those you would still use insert and use a for loop to initialize tempVector or use an array:
double tempVector_init[] = {0.0,1.0,2.0};
vector<double> tempVector(tempVector_init,tempVector_init+3);
std::set<A> mySet;
for (uint i = 0; i < (uint) 10; i++)
{
myset.insert(A(i+1,tempVector));
}
I have an array int arr[5] that is passed to a function fillarr(int arr[]):
int fillarr(int arr[])
{
for(...);
return arr;
}
How can I return that array?
How will I use it, say I returned a pointer how am I going to access it?
In this case, your array variable arr can actually also be treated as a pointer to the beginning of your array's block in memory, by an implicit conversion. This syntax that you're using:
int fillarr(int arr[])
Is kind of just syntactic sugar. You could really replace it with this and it would still work:
int fillarr(int* arr)
So in the same sense, what you want to return from your function is actually a pointer to the first element in the array:
int* fillarr(int arr[])
And you'll still be able to use it just like you would a normal array:
int main()
{
int y[10];
int *a = fillarr(y);
cout << a[0] << endl;
}
C++ functions can't return C-style arrays by value. The closest thing is to return a pointer. Furthermore, an array type in the argument list is simply converted to a pointer.
int *fillarr( int arr[] ) { // arr "decays" to type int *
return arr;
}
You can improve it by using an array references for the argument and return, which prevents the decay:
int ( &fillarr( int (&arr)[5] ) )[5] { // no decay; argument must be size 5
return arr;
}
With Boost or C++11, pass-by-reference is only optional and the syntax is less mind-bending:
array< int, 5 > &fillarr( array< int, 5 > &arr ) {
return arr; // "array" being boost::array or std::array
}
The array template simply generates a struct containing a C-style array, so you can apply object-oriented semantics yet retain the array's original simplicity.
In C++11, you can return std::array.
#include <array>
using namespace std;
array<int, 5> fillarr(int arr[])
{
array<int, 5> arr2;
for(int i=0; i<5; ++i) {
arr2[i]=arr[i]*2;
}
return arr2;
}
$8.3.5/8 states-
"Functions shall not have a return type of type array or function, although they may have a return type of type pointer or reference to such things. There shall be no arrays of functions, although there can be arrays of pointers to functions."
int (&fn1(int (&arr)[5]))[5]{ // declare fn1 as returning refernce to array
return arr;
}
int *fn2(int arr[]){ // declare fn2 as returning pointer to array
return arr;
}
int main(){
int buf[5];
fn1(buf);
fn2(buf);
}
the answer may depend a bit on how you plan to use that function. For the simplest answer, lets decide that instead of an array, what you really want is a vector. Vectors are nice because the look for all the world like boring, ordinary values you can store in regular pointers. We'll look at other options and why you want them afterwards:
std::vector<int> fillarr( std::vector<int> arr ) {
// do something
return arr;
}
This will do exactly what you expect it to do. The upside is that std::vector takes care of making sure everything is handled cleanly. the downside is that this copies a very large amount of data, if your array is large. In fact it copies every element of the array twice. first it copies the vector so that the function can use it as a parameter. then it copies it again to return it to the caller. If you can handle managing the vector yourself, you can do things quite a bit more easily. (it may copy it a third time if the caller needs to store it in a variable of some sort to do more calculation)
It looks like what you're really trying to do is just populate a collection. if you don't have a specific reason to return a new instance of a collection, then don't. we can do it like this
void fillarr(std::vector<int> & arr) {
// modify arr
// don't return anything
}
this way you get a reference to the array passed to the function, not a private copy of it. any changes you make to the parameter are seen by the caller. You could return a reference to it if you want, but that's not really a great idea, since it sort of implies that you're getting something different from what you passed.
If you really do need a new instance of the collection, but want to avoid having it on the stack (and all the copying that entails), you need to create some kind of contract for how that instance is handled. the easiest way to do that is to use a smart pointer, which keeps the referenced instance around as long as anyone is holding onto it. It goes away cleanly if it goes out of scope. That would look like this.
std::auto_ptr<std::vector<int> > fillarr( const std::vector<int> & arr) {
std::auto_ptr<std::vector<int> > myArr(new std::vector<int>);
// do stuff with arr and *myArr
return myArr;
}
For the most part, using *myArr works identically to using a plain vanilla vector. This example also modifies the parameter list by adding the const keyword. Now you get a reference without copying it, but you can't modify it, so the caller knows it'll be the same as before the function got to it.
All of this is swell, but idiomatic c++ rarely works with collections as a whole. More normally, you will be using iterators over those collections. that would look something more like this
template <class Iterator>
Iterator fillarr(Iterator arrStart, Iterator arrEnd) {
Iterator arrIter = arrStart;
for(;arrIter <= arrEnd; arrIter++)
;// do something
return arrStart;
}
Using it looks a bit odd if you're not used to seeing this style.
vector<int> arr;
vector<int>::iterator foo = fillarr(arr.begin(), arr.end());
foo now 'points to' the beginning of the modified arr.
What's really nice about this is that it works equally well on vector as on plain C arrays and many other types of collection, for example
int arr[100];
int *foo = fillarr(arr, arr+100);
Which now looks an awful lot like the plain pointer examples given elsewhere in this question.
This:
int fillarr(int arr[])
is actually treated the same as:
int fillarr(int *arr)
Now if you really want to return an array you can change that line to
int * fillarr(int arr[]){
// do something to arr
return arr;
}
It's not really returning an array. you're returning a pointer to the start of the
array address.
But remember when you pass in the array, you're only passing in a pointer.
So when you modify the array data, you're actually modifying the data that the
pointer is pointing at. Therefore before you passed in the array, you must realise
that you already have on the outside the modified result.
e.g.
int fillarr(int arr[]){
array[0] = 10;
array[1] = 5;
}
int main(int argc, char* argv[]){
int arr[] = { 1,2,3,4,5 };
// arr[0] == 1
// arr[1] == 2 etc
int result = fillarr(arr);
// arr[0] == 10
// arr[1] == 5
return 0;
}
I suggest you might want to consider putting a length into your fillarr function like
this.
int * fillarr(int arr[], int length)
That way you can use length to fill the array to it's length no matter what it is.
To actually use it properly. Do something like this:
int * fillarr(int arr[], int length){
for (int i = 0; i < length; ++i){
// arr[i] = ? // do what you want to do here
}
return arr;
}
// then where you want to use it.
int arr[5];
int *arr2;
arr2 = fillarr(arr, 5);
// at this point, arr & arr2 are basically the same, just slightly
// different types. You can cast arr to a (char*) and it'll be the same.
If all you're wanting to do is set the array to some default values, consider using
the built in memset function.
something like:
memset((int*)&arr, 5, sizeof(int));
While I'm on the topic though. You say you're using C++. Have a look at using stl vectors. Your code is likely to be more robust.
There are lots of tutorials. Here is one that gives you an idea of how to use them.
http://www.yolinux.com/TUTORIALS/LinuxTutorialC++STL.html
This is a fairly old question, but I'm going to put in my 2 cents as there are a lot of answers, but none showing all possible methods in a clear and concise manner (not sure about the concise bit, as this got a bit out of hand. TL;DR 😉).
I'm assuming that the OP wanted to return the array that was passed in without copying as some means of directly passing this to the caller to be passed to another function to make the code look prettier.
However, to use an array like this is to let it decay into a pointer and have the compiler treat it like an array. This can result in subtle bugs if you pass in an array like, with the function expecting that it will have 5 elements, but your caller actually passes in some other number.
There a few ways you can handle this better. Pass in a std::vector or std::array (not sure if std::array was around in 2010 when the question was asked). You can then pass the object as a reference without any copying/moving of the object.
std::array<int, 5>& fillarr(std::array<int, 5>& arr)
{
// (before c++11)
for(auto it = arr.begin(); it != arr.end(); ++it)
{ /* do stuff */ }
// Note the following are for c++11 and higher. They will work for all
// the other examples below except for the stuff after the Edit.
// (c++11 and up)
for(auto it = std::begin(arr); it != std::end(arr); ++it)
{ /* do stuff */ }
// range for loop (c++11 and up)
for(auto& element : arr)
{ /* do stuff */ }
return arr;
}
std::vector<int>& fillarr(std::vector<int>& arr)
{
for(auto it = arr.begin(); it != arr.end(); ++it)
{ /* do stuff */ }
return arr;
}
However, if you insist on playing with C arrays, then use a template which will keep the information of how many items in the array.
template <size_t N>
int(&fillarr(int(&arr)[N]))[N]
{
// N is easier and cleaner than specifying sizeof(arr)/sizeof(arr[0])
for(int* it = arr; it != arr + N; ++it)
{ /* do stuff */ }
return arr;
}
Except, that looks butt ugly, and super hard to read. I now use something to help with that which wasn't around in 2010, which I also use for function pointers:
template <typename T>
using type_t = T;
template <size_t N>
type_t<int(&)[N]> fillarr(type_t<int(&)[N]> arr)
{
// N is easier and cleaner than specifying sizeof(arr)/sizeof(arr[0])
for(int* it = arr; it != arr + N; ++it)
{ /* do stuff */ }
return arr;
}
This moves the type where one would expect it to be, making this far more readable. Of course, using a template is superfluous if you are not going to use anything but 5 elements, so you can of course hard code it:
type_t<int(&)[5]> fillarr(type_t<int(&)[5]> arr)
{
// Prefer using the compiler to figure out how many elements there are
// as it reduces the number of locations where you have to change if needed.
for(int* it = arr; it != arr + sizeof(arr)/sizeof(arr[0]); ++it)
{ /* do stuff */ }
return arr;
}
As I said, my type_t<> trick wouldn't have worked at the time this question was asked. The best you could have hoped for back then was to use a type in a struct:
template<typename T>
struct type
{
typedef T type;
};
typename type<int(&)[5]>::type fillarr(typename type<int(&)[5]>::type arr)
{
// Prefer using the compiler to figure out how many elements there are
// as it reduces the number of locations where you have to change if needed.
for(int* it = arr; it != arr + sizeof(arr)/sizeof(arr[0]); ++it)
{ /* do stuff */ }
return arr;
}
Which starts to look pretty ugly again, but at least is still more readable, though the typename may have been optional back then depending on the compiler, resulting in:
type<int(&)[5]>::type fillarr(type<int(&)[5]>::type arr)
{
// Prefer using the compiler to figure out how many elements there are
// as it reduces the number of locations where you have to change if needed.
for(int* it = arr; it != arr + sizeof(arr)/sizeof(arr[0]); ++it)
{ /* do stuff */ }
return arr;
}
And then of course you could have specified a specific type, rather than using my helper.
typedef int(&array5)[5];
array5 fillarr(array5 arr)
{
// Prefer using the compiler to figure out how many elements there are
// as it reduces the number of locations where you have to change if needed.
for(int* it = arr; it != arr + sizeof(arr)/sizeof(arr[0]); ++it)
{ /* do stuff */ }
return arr;
}
Back then, the free functions std::begin() and std::end() didn't exist, though could have been easily implemented. This would have allowed iterating over the array in a safer manner as they make sense on a C array, but not a pointer.
As for accessing the array, you could either pass it to another function that takes the same parameter type, or make an alias to it (which wouldn't make much sense as you already have the original in that scope). Accessing a array reference is just like accessing the original array.
void other_function(type_t<int(&)[5]> x) { /* do something else */ }
void fn()
{
int array[5];
other_function(fillarr(array));
}
or
void fn()
{
int array[5];
auto& array2 = fillarr(array); // alias. But why bother.
int forth_entry = array[4];
int forth_entry2 = array2[4]; // same value as forth_entry
}
To summarize, it is best to not allow an array decay into a pointer if you intend to iterate over it. It is just a bad idea as it keeps the compiler from protecting you from shooting yourself in the foot and makes your code harder to read. Always try and help the compiler help you by keeping the types as long as possible unless you have a very good reason not to do so.
Edit
Oh, and for completeness, you can allow it to degrade to a pointer, but this decouples the array from the number of elements it holds. This is done a lot in C/C++ and is usually mitigated by passing the number of elements in the array. However, the compiler can't help you if you make a mistake and pass in the wrong value to the number of elements.
// separate size value
int* fillarr(int* arr, size_t size)
{
for(int* it = arr; it != arr + size; ++it)
{ /* do stuff */ }
return arr;
}
Instead of passing the size, you can pass the end pointer, which will point to one past the end of your array. This is useful as it makes for something that is closer to the std algorithms, which take a begin and and end pointer, but what you return is now only something that you must remember.
// separate end pointer
int* fillarr(int* arr, int* end)
{
for(int* it = arr; it != end; ++it)
{ /* do stuff */ }
return arr;
}
Alternatively, you can document that this function will only take 5 elements and hope that the user of your function doesn't do anything stupid.
// I document that this function will ONLY take 5 elements and
// return the same array of 5 elements. If you pass in anything
// else, may nazal demons exit thine nose!
int* fillarr(int* arr)
{
for(int* it = arr; it != arr + 5; ++it)
{ /* do stuff */ }
return arr;
}
Note that the return value has lost it's original type and is degraded to a pointer. Because of this, you are now on your own to ensure that you are not going to overrun the array.
You could pass a std::pair<int*, int*>, which you can use for begin and end and pass that around, but then it really stops looking like an array.
std::pair<int*, int*> fillarr(std::pair<int*, int*> arr)
{
for(int* it = arr.first; it != arr.second; ++it)
{ /* do stuff */ }
return arr; // if you change arr, then return the original arr value.
}
void fn()
{
int array[5];
auto array2 = fillarr(std::make_pair(&array[0], &array[5]));
// Can be done, but you have the original array in scope, so why bother.
int fourth_element = array2.first[4];
}
or
void other_function(std::pair<int*, int*> array)
{
// Can be done, but you have the original array in scope, so why bother.
int fourth_element = array2.first[4];
}
void fn()
{
int array[5];
other_function(fillarr(std::make_pair(&array[0], &array[5])));
}
Funny enough, this is very similar to how std::initializer_list work (c++11), but they don't work in this context.
to return an array from a function , let us define that array in a structure;
So it looks something like this
struct Marks{
int list[5];
}
Now let us create variables of the type structure.
typedef struct Marks marks;
marks marks_list;
We can pass array to a function in the following way and assign value to it:
void setMarks(int marks_array[]){
for(int i=0;i<sizeof(marks_array)/sizeof(int);i++)
marks_list.list[i]=marks_array[i];
}
We can also return the array. To return the array , the return type of the function should be of structure type ie marks. This is because in reality we are passing the structure that contains the array. So the final code may look like this.
marks getMarks(){
return marks_list;
}
the Simplest way to do this ,is to return it by reference , even if you don't write
the '&' symbol , it is automatically returned by reference
void fillarr(int arr[5])
{
for(...);
}
int *fillarr(int arr[])
You can still use the result like
int *returned_array = fillarr(some_other_array);
if(returned_array[0] == 3)
do_important_cool_stuff();
As above mentioned paths are correct. But i think if we just return a local array variable of a function sometimes it returns garbage values as its elements.
in-order to avoid that i had to create the array dynamically and proceed. Which is something like this.
int* func()
{
int* Arr = new int[100];
return Arr;
}
int main()
{
int* ArrResult = func();
cout << ArrResult[0] << " " << ArrResult[1] << endl;
return 0;
}
Source: https://www.tutorialspoint.com/cplusplus/cpp_return_arrays_from_functions.htm
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:
int * myFunction() {
.
.
.
}
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.
Applying these rules on the current question, we can write the program as follows:
# include <iostream>
using namespace std;
int * fillarr( );
int main ()
{
int *p;
p = fillarr();
for ( int i = 0; i < 5; i++ )
cout << "p[" << i << "] : "<< *(p + i) << endl;
return 0;
}
int * fillarr( )
{
static int arr[5];
for (int i = 0; i < 5; ++i)
arr[i] = i;
return arr;
}
The Output will be:
p[0]=0
p[1]=1
p[2]=2
p[3]=3
p[4]=4
template<typename T, size_t N>
using ARR_REF = T (&)[N];
template <typename T, size_t N>
ARR_REF<T,N> ArraySizeHelper(ARR_REF<T,N> arr);
#define arraysize(arr) sizeof(ArraySizeHelper(arr))
and what about:
int (*func())
{
int *f = new int[10] {1,2,3};
return f;
}
int fa[10] = { 0 };
auto func2() -> int (*) [10]
{
return &fa;
}
Actually when you pass an array inside a function, the pointer to the original array is passed in the function parameter and thus the changes made to the array inside that function is actually made on the original array.
#include <iostream>
using namespace std;
int* func(int ar[])
{
for(int i=0;i<100;i++)
ar[i]=i;
int *ptr=ar;
return ptr;
}
int main() {
int *p;
int y[100]={0};
p=func(y);
for(int i=0;i<100;i++)
cout<<i<<" : "<<y[i]<<'\n';
}
Run it and you will see the changes
And why don't "return" the array as a parameter?
fillarr(int source[], size_t dimSource, int dest[], size_t dimDest)
{
if (dimSource <= dimDest)
{
for (size_t i = 0; i < dimSource; i++)
{
//some stuff...
}
}
else
{
//some stuff..
}
}
or..in a simpler way (but you have to know the dimensions...):
fillarr(int source[], int dest[])
{
//...
}
A simple and elaborate example, so that I can refer here if I forget the concept and need help.
#include <iostream>
using namespace std;
int *ReturnArray(int arr[], int size)
{
static int MinMax[2] = {0, 0}; // must use static, else address would be deleted after the return is reached
MinMax[0] = arr[0];
MinMax[1] = arr[size - 1];
return MinMax;
}
int main()
{
int arr[] = {1, 2, 3};
int size = sizeof(arr) / sizeof(*arr);
int *ans; // pointer to hold returned array
ans = ReturnArray(arr, size); // only pointer can receive the return, not an array
cout << "Min: " << ans[0] << " Max: " << ans[1];
return 0;
}
Here's a full example of this kind of problem to solve
#include <bits/stdc++.h>
using namespace std;
int* solve(int brr[],int n)
{
sort(brr,brr+n);
return brr;
}
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
int *a=solve(arr,n);
for(int i=0;i<n;i++)
{
cout<<a[i]<<endl;
}
return 0;
}
i used static array so that while returning array it should not throw error as you are returning address of local variable...
so now you can send any locally created variable from function by making it as static...as it works as global variable....
#include<iostream>
using namespace std;
char *func(int n)
{
// char a[26]; /*if we use this then an error will occur because you are
// returning address of a local variable*/
static char a[26];
char temp='A';
for(int i=0;i<n;i++)
{
a[i]=temp;temp++;
}
return a;
}
int main()
{
int n=26;
char *p=func(n);
for(int i=0;i<n;i++)
cout<<*(p+i)<<" ";
//or you can also print like this
for(int i=0;i<n;i++)
cout<<p[i]<<" ";
}
Just define a type[ ] as return value, like:
private string[] functionReturnValueArray(string one, string two)
{
string[] x = {one, two};
x[0] = "a";
x[1] = "b";
return x;
}
.
.
.
function call:
string[] y;
y = functionReturnValueArray(stringOne, stringTwo)