473,394 Members | 1,750 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

ARRAYS FUNCTIONS

How to return an array from a function?

Dec 6 '05 #1
7 1288
coinjo wrote:

Don't use all caps in the subject line.
How to return an array from a function?


[we should have a faq on this]

http://tinyurl.com/7ne54
Jonathan

Dec 6 '05 #2
"coinjo" <co****@gmail.com> writes:
How to return an array from a function?


Several alternatives:

1. Use std::vector<>

std::vector<int> func(size_t sz)
{
std::vector<int> vec;
vec.reserve(sz);
for (size_t i = 0; i < sz; ++i) {
vec.push_back(i);
}
return vec;
}

2. Let the caller define the array and pass it as an argument:

void func(int* arr, size_t sz)
{
for (size_t i = 0; i < sz; ++i) {
arr[i] = i;
}
}

3. Let the function allocate an array and pass it back:

int* func(size_t sz)
{
int* arr = malloc(sz * sizeof *arr);
for (size_t i = 0; i < sz; ++i) {
arr[i] = i;
}
}

Alternative 3 is the most complex, since the caller will be
responsible for freeing the array. This needs a careful
analysis of ownership and lifetime issues.

/Niklas Norrthon
Dec 6 '05 #3
Niklas Norrthon <do********@invalid.net> writes:
3. Let the function allocate an array and pass it back:

int* func(size_t sz)
{
int* arr = malloc(sz * sizeof *arr);
for (size_t i = 0; i < sz; ++i) {
arr[i] = i;
}
}


Sorry for replying to my own post, but the above is C and not C++
of course. In C++ the value returned by malloc must be cast. But
better is:

int* func(size_t sz)
{
int* arr = new int[sz];
for (size_t i = 0; i < sz; ++i) {
arr[i] = i;
}
}

And the caller must free the array with delete[] sz;
To my defence I can only say that I commonly use malloc in C
and rarely new [], and delete [] in C++, where I usually
choose one of the container classes instead.

/Niklas Norrthon
Dec 6 '05 #4

Niklas Norrthon wrote in message <0p************@niklas.ua.dynas.se>...
Niklas Norrthon <do********@invalid.net> writes:
3. Let the function allocate an array and pass it back:

[snip]
Sorry for replying to my own post, but the above is C and not C++
of course. In C++ the value returned by malloc must be cast. But
better is:

int* func(size_t sz){
int* arr = new int[sz];
for (size_t i = 0; i < sz; ++i) { arr[i] = i;}
}

And the caller must free the array with delete[] sz;
To my defence I can only say that I commonly use malloc in C
and rarely new [], and delete [] in C++, where I usually
choose one of the container classes instead.
/Niklas Norrthon


The way I see it, 'sz' is passed into the func 'by value'. That means a
temporary 'sz' is created in the func and destroyed when the func returns.
But, that is one thing, losing track of the newed memory is going to leave
you with no way to delete it. You promised to return an 'int*', but didn't.

int* func(size_t sz){
int* arr = new int[sz];
for(size_t i(0); i < sz; ++i) { arr[i] = i; }
return arr;
}
// ......
int *MyArray( func( 10 ) );
for(size_t i(0); i < 10; ++i){ std::cout<<MyArray[i]<<std::endl;}
// ......
delete [] MyArray;

--
Bob R
POVrookie

Dec 7 '05 #5
"BobR" <Re***********@worldnet.att.net> writes:
Niklas Norrthon wrote in message <0p************@niklas.ua.dynas.se>...
Niklas Norrthon <do********@invalid.net> writes:
3. Let the function allocate an array and pass it back:[snip]
Sorry for replying to my own post, but the above is C and not C++
of course. In C++ the value returned by malloc must be cast. But
better is:

int* func(size_t sz){
int* arr = new int[sz];
for (size_t i = 0; i < sz; ++i) { arr[i] = i;}
}

And the caller must free the array with delete[] sz;
To my defence I can only say that I commonly use malloc in C
and rarely new [], and delete [] in C++, where I usually
choose one of the container classes instead.
/Niklas Norrthon


The way I see it, 'sz' is passed into the func 'by value'. That means a
temporary 'sz' is created in the func and destroyed when the func returns.


It's the local sz is destroyed, but the function was called from somewhere,
and the caller of the function knows what sz is, so what's the problem?
But, that is one thing, losing track of the newed memory is going to leave
you with no way to delete it. You promised to return an 'int*', but didn't.


My mistake. I typed too quick, correcting the mistake in my previous code.
Luckily though, the compiler would have caught this one.

/Niklas Norrthon
Dec 7 '05 #6

Niklas Norrthon wrote in message <0p************@niklas.ua.dynas.se>...
"BobR" <Re***********@worldnet.att.net> writes:
Niklas Norrthon wrote in message <0p************@niklas.ua.dynas.se>...
>int* func(size_t sz){
> int* arr = new int[sz];
> for (size_t i = 0; i < sz; ++i) { arr[i] = i;}
>}
>And the caller must free the array with delete[] sz; [snip] >/Niklas Norrthon


The way I see it, 'sz' is passed into the func 'by value'. That means a
temporary 'sz' is created in the func and destroyed when the func returns.


It's the local sz is destroyed, but the function was called from somewhere,
and the caller of the function knows what sz is, so what's the problem?


The problem was this line:
"And the caller must free the array with delete[] sz;"

I assume it was a 'typo', otherwise the OP might think you should do (in
main):

size_t ArrSz(23);
int *MyArray( func( ArrSz ) );
// .........
// delete [] MyArray; // correct way
delete [] ArrSz; // Bbzzzzztt, TROUBLE!

I'm sure you know you don't 'delete[]' a number when you meant to delete the
memory used by the array, but, a person just starting C++ might not.
We 'good' on this one now? :-}
--
Bob R
POVrookie
Dec 7 '05 #7
"BobR" <Re***********@worldnet.att.net> writes:
The problem was this line:
"And the caller must free the array with delete[] sz;"

I assume it was a 'typo', otherwise the OP might think you should do (in
main):


Of course it was a typo, and since I know what I meant, I read it as
what I meant.

/Niklas Norrthon
Dec 8 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Jason | last post by:
I have a number of arrays that are populated with database values. I need to determine which array has the highest ubound out of all the arrays. The array size will always change based on the...
7
by: csx | last post by:
Hi everyone! two quick questions relating to arrays. Q1, Is it possible to re-assign array elements? int array = {{2,4}, {4,5}}; array = {2,3}
19
by: Canonical Latin | last post by:
"Leor Zolman" <leor@bdsoft.com> wrote > "Canonical Latin" <javaplus@hotmail.com> wrote: > > > ... > >But I'm still curious as to the rational of having type >...
7
by: Kieran Simkin | last post by:
I have in my project in main.c a number of arrays defined like this (outside of any functions): char muser, mpass; I'm declaring them in a number of other .c files (inside functions) like this:...
16
by: mike3 | last post by:
(I'm xposting this to both comp.lang.c++ and comp.os.ms- windows.programmer.win32 since there's Windows material in here as well as questions related to standard C++. Not sure how that'd go over...
8
by: Spoon | last post by:
Hello, Could someone explain why the following code is illegal? (I'm trying to use a list of (C-style) arrays.) #include <list> typedef std::list < int foo_t; int main() { int v = { 12, 34...
29
weaknessforcats
by: weaknessforcats | last post by:
Arrays Revealed Introduction Arrays are the built-in containers of C and C++. This article assumes the reader has some experiece with arrays and array syntax but is not clear on a )exactly how...
127
by: sanjay.vasudevan | last post by:
Why are the following declarations invalid in C? int f(); int f(); It would be great if anyone could also explain the design decision for such a language restricton. Regards, Sanjay
152
by: vippstar | last post by:
The subject might be misleading. Regardless, is this code valid: #include <stdio.h> void f(double *p, size_t size) { while(size--) printf("%f\n", *p++); } int main(void) { double array = { {...
0
by: datapata | last post by:
Hi I have some C++ code that I need to access from Python. I don't need to access any classes or anything, just a couple of functions that take one array as input and produce another array as...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.