1

I want to create a function that takes an integer as it's parameter and returns an array in C++. This is the pseudo-code I had in mind:

function returnarray(integer i)
{
    integer intarr[i];

    for (integer j = 0; j < i; j++) { intarr[j] = j; }

    return intarr;
}

I tried the common way of declaring returnarray as function* returning a pointer, but then I can't take an integer as my parameter. I also can't assign j to intarr[j]. I'd really like to avoid making a pointer to an int just so I could use the parameter.

Is there any way of doing this and being able to assign j to intarr[j] without making a pointer for it?

EDIT:

forgot to write that I want to avoid vectors. I use them only if I really have to! (my reasons are mine).

Thanks :D

13
  • 3
    You need to state your reasons for wishing to avoid vectors. A vector provides an obvious solution; answerers need to know what restrictions on potential solutions you are imposing. Commented Dec 18, 2010 at 21:52
  • 5
    @MisterSir: If you want to improve your understanding of C++, you need to tackle a problem which has a solution that you don't already understand- for example, implementing vector. Solving easy problems with strange solutions won't improve your understanding of the language in any meaningful fashion. Commented Dec 18, 2010 at 22:25
  • 3
    How about: "the reason I don't want to use a vector is that I am implementing a vector replacement as a learning exercise". That would have been clearer. I still don't understand what you are trying to do, though, as no part of the interface of vector requires you to have to return an array. Commented Dec 18, 2010 at 22:58
  • 2
    @MisterSir: "Just an easy way out"?! Driving a car or taking public transit is "just an easy way out", I hope you walk across your country so you can "actually learn something" instead of getting things done. Commented Dec 18, 2010 at 23:06
  • 2
    @MisterSir: Because doing resource management by hand is not idiomatic C++. Switching from malloc to new does not make you a C++ programmer, your code is basically still C. Commented Dec 19, 2010 at 8:52

5 Answers 5

10

You can't return a stack-allocated array- it's going to go out of scope and the memory deallocated. In addition, C++ does not allow stack-allocated variable-length arrays. You should use a std::vector.

std::vector<int> returnarray(int i) {
    std::vector<int> ret(i);
    for(int j = 0; j < i; j++) ret[j] = j;
    return ret;
}
Sign up to request clarification or add additional context in comments.

5 Comments

If you are comfortable with STL Vectors are great. If you are more familiar with C code my answer is more "old school" its a matter of taste, each method has their pros and cons
+1 for the concise answer, though I'm wondering if there's any additional benefit to be had in returning a const std::vector<int>?
@EnabrenTane: No, that's not actually true at all. Your method has a gigantic list of program-ruining cons. Like, no bounds checking, no exception safety, no automatic release, no semantic enforcement. The only advantage it has is cross-compiler/cross-language link ability. And every C++ programmer should be comfortable with the STL vector. The incredible failings of that answer are the entire reason that these C++ concepts exist. @ig2r: No, there's none to be had.
C "Speed first and safety if there is time"
@Enabren: Except you could have both speed and safety with a vector.
5

your code isn't even near valid c++ so i assume you're total beginner

use std::vector

#include <vector>

std::vector<int> yourFunction( int n )
{
    std::vector<int>  result;
    for( int i = 0;  i < n;  ++i )
    {
        result.push_back( i );
    }
    return result;
}

Disclaimer: code untouched by compilers' hands.

Cheers & hth.,

5 Comments

It's just pseudo-code meant to show what I'm trying to do. I could just use a vector, but I also forgot to write that I want to avoid vectors. It's possible to use them, but it will just make my code more complicated because I'm in need to approach arrays directly. Thanks anyways though.
@MisterSir: Using std::vector will make your code simpler, not more complicated. For a start it is not possible to have a function that returns an array so you have to do something else. Returning a std::vector is the simplest alternative in almost every respect.
Consider result.reserve(n) . Otherwise push_back will have poor performance for large values of n. Depending on the implementation usually vectors grow by about 1.5 to 2x. meaning you will have to reallocate and memcpy repeatedly.
@EnabrenTane: there is no need to use reserve here, because the desired size can be simply be used as constructor argument (see @DeadMG's answer). I chose to illustrate push_back because the OP could learn something useful from that. I chose to not illustrate premature optimization because the OP would learn the Wrong Thing from that. But as it turned out, the OP didn't learn from any of the std::vector answers. So, the effort to compose good answer was in vain.
@EnabrenTane: also, as illustration of what I mean by "learning the Wrong Thing", the possible poor performance is for small values of n, not for large ones. You've learned something wrong somewhere.
1

Two remarks, before using the excellent @DeadMG 's solution:

1) You never want to avoid vectors. If v is a vector, and you really want a pointer, you can always have a pointer to the first element by writing &v[0].

2) You can't return an array. You will return a pointer to a fresh memory zone that you'll have to delete once finished with it. Vectors are only arrays with an automatic deletion facility, so you won't leak memory.

Comments

0

You need to use dynamic memory. Something like this

int* returnArray(int size) {
    int* array = new int[size];
    for(int i = 0; i < size; ++i)
        array[i] = i;
    return array;
}

9 Comments

Don't forget to initialize the values in the array (as per posted pseudo-code) :)
-1 This is ungood because it teaches beginner to use raw pointers and new and delete, dealing manually with lifetimes. it just stops leaning for a long time because the beginner has to deal with mostly extraneous issues. then later the person has to unlearn all that stuff.
I respectfully disagree. Learning how to use raw pointers is one of the most important skills a programmer can possibly have. I was taught pointers in week 3 at Digipen ( not that I immediately understood them)
@EnabrenTane: Learning how to use raw pointers is important, but they're not always the best starting point for a beginner. It's often better to learn how to use something like vector first, and then worry about how it's implemented internally.
@Maxpm: No, delete p will result in undefined behavior. The array has to be released via delete[] p. What do you think is easier, teaching a beginner the usage of std::vector or the concept of undefined behavior?
|
0

Not that I'd particularly recommend this approach in general, but you can use templates to do this without resorting to dynamic memory allocation. Unfortunately you can't return arrays from functions, so you'd need to return a struct with the array inside.

template <int N>
struct int_array_type {
    int ints[N];
};

template <int N>
int_array_type<N> returnarray() {
    int_array_type<N> a;
    for (int i = 0; i < N; ++i)
        a.ints[i] = i;
    return a;
}

...

int_array_type<10> u = returnarray<10>();
std::copy(u.ints, u.ints+sizeof(u.ints)/sizeof(u.ints[0]),
    std::ostream_iterator<int>(std::cout, "\n"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.