[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.c++

How to return a pointer to an array?

mani

10/18/2008 11:57:00 AM

int (*nVar)[10]..This is the variable i used in a function.. i
tried ...nothing worked.. anyone please tell me how to return it....
3 Answers

Pranav

10/18/2008 1:29:00 PM

0

On Oct 18, 4:56 pm, mani <manigand...@gmail.com> wrote:
> int (*nVar)[10]..This is the variable i used in a function.. i
> tried ...nothing worked.. anyone please tell me how to return it....

Just return nVar.....,

Salt_Peter

10/18/2008 1:41:00 PM

0

On Oct 18, 7:56 am, mani <manigand...@gmail.com> wrote:
> int (*nVar)[10]..This is the variable i used in a function.. i
> tried ...nothing worked.. anyone please tell me how to return it....

Show minimum, compileable code please.
We don't know if what you have is a local array and a dangling
pointer.
Prefer const references. Prefer std::vector<> over fixed arrays.

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

template< typename T >
void foo( const std::vector< T >& r_v )
{
std::copy( r_v.begin(),
r_v.end(),
std::ostream_iterator< T >(std::cout, " ") );
std::cout << std::endl;
}

int main()
{
std::vector< int > vn(10, 99);
foo( vn );
}

/*
99 99 99 99 99 99 99 99 99 99
*/

The above should really be an operator<<
If you prefer working with dumb fixed arrays:

template< typename T, const std::size_t Size >
void bar( const T (& r_a)[ Size ] )
{
for( std::size_t i = 0; i < Size; ++i)
{
std::cout << r_a[i];
std::cout << " ";
}
std::cout << std::endl;
}

int main()
{
int array[10] = { 0 };
bar( array );
}

/*
0 0 0 0 0 0 0 0 0 0
*/

blargg.h4g

10/18/2008 4:11:00 PM

0

In article
<2be38d55-4704-4ae5-a2db-7abf5681bbbe@40g2000prx.googlegroups.com>, mani
<manigandane@gmail.com> wrote:

> int (*nVar)[10]..This is the variable i used in a function.. i
> tried ...nothing worked.. anyone please tell me how to return it....

I recommend avoiding C-style arrays, especially pointers to them, as
you'll quickly get lost in the details. But if you insist, this code shows
how:

#include <iostream>

typedef int i10 [10];

i10* func()
{
i10* p = new i10 [1]; // int (*p) [10] = new int [1] [10]
(*p) [0] = 1234;
// ...
(*p) [9] = 5678;
return p;
}

int main()
{
i10* p = func();
std::cout << (*p) [0] << '\n';
// ...
std::cout << (*p) [9] << '\n';
delete [] p;
}