0

this my program to return array from function in c++

#include <iostream>
using namespace std;

int *pTest(){
    static int a[] = {2,3,4,6,9};
    return a;
}

int main(){
    int *x;
    x = pTest();
    while(*x != NULL){
        cout << *x++ << "  ";
    }
}

according to me output should be 2 3 4 6 9
but on my machine output is 2 3 4 6 9 1,
why there is an extra 1 in the output.
i am using codeblocks ,gcc 4.8.1

3
  • 5
    Arrays don't have an implicit zero element. What would that mean if you had, say, struct S {S(int);}; and an array of S? Commented Oct 6, 2014 at 18:16
  • 2
    You should use container classes (e.g. std::vector for dynamically sized or std::array for fixed size) Commented Oct 6, 2014 at 18:18
  • You don't tell the loop when to stop. It is only string literals that put a NULL character in automatically. Try: static int a[] = {2,3,4,6,9,0}; Commented Oct 6, 2014 at 19:06

3 Answers 3

6

Arrays aren't zero-terminated, so the loop while (*x != NULL) will keep reading beyond the array until it finds a zero-valued word, or crashes, or causes some other undefined behaviour.

You'll either need to add a terminator to the array (if you can choose a value, perhaps zero, that won't be a valid array element), or return the length in some other way.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use a count and take the size of the array. Like this:

int k = 0;
while(k <= sizeof(x)){
    cout  << "  "<< *x++;
    k++;

}

1 Comment

That is not correct. sizeof(x) will evaluate to sizeof(int*). Not what you are expecting to find.
0

With std::vector your function will be:

std::vector<int> ptest() {
    static const int a[] = {2,3,4,6,9};
    std::vector<int> vec (a, a + sizeof(a) / sizeof(a[0]) );
    return vec;
}

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.