C
coinjo
How to return an array from a function?
How to return an array from a function?
coinjo said:How to return an array from a function?
Niklas Norrthon said: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;
}
}
Niklas Norrthon wrote in message said:[snip]Niklas Norrthon said:3. Let the function allocate an array and pass it back:
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;}
}
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
BobR said:Niklas Norrthon wrote in message said:[snip]Niklas Norrthon said:3. Let the function allocate an array and pass it back:
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;}
}
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.
Niklas Norrthon wrote in message said:BobR said:Niklas Norrthon wrote in message said:int* func(size_t sz){
int* arr = new int[sz];
for (size_t i = 0; i < sz; ++i) { arr = 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?
BobR said: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):
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.