user2935569
user2935569

Reputation: 347

returning array using functions - c++

I am trying to pass an array in a function and then printing it out the values found inside the array.

this is what I have

numbers.cpp

#include <iostream>
#include <string>
#include "numbers.h"

int * numbers::printNumbers()    {

    for (int i=0; i<3; i++) {
        for (int j=0; j<3; j++) {
            arrayOne[j] =i;
        }
    }
    return arrayOne;
}

numbers.h

#ifndef try_numbers_h
#define try_numbers_h
#include <iostream>
#include <string>

class numbers   {

public:

      int * printNumbers();

private:

      int arrayOne[4];
};

#endif

main.cpp

#include <iostream>
#include <string>
#include "numbers.h"

int main () {
    numbers printNum;
    int * p;
    p = printNum.printNumbers();

}

the codes shown above, run successfully

but my output is returning some weird memory address

output

0x7fff5fbff8e0 

by right it should output

expect output

0
1
2
3

Upvotes: 1

Views: 94

Answers (2)

jrd1
jrd1

Reputation: 10726

Your code is correct.

The memory address it is printing is the address of the beginning of the class variable arrayOne. The reason you are seeing that instead of:

0
1
2
3

Is that this bit of code:

numbers printNum;
int * p;
p = printNum.printNumbers();

is only being assigned the address of the array arrayOne, not the value of its contents.

Which brings us to another issue: you are not seeing any output as you are not printing out the data at each array index (as shown in your code).

To do so, you should iterate over the pointer to the array arrayOne and output them so you can see/verify your expected results.

However, as your current methodology violates the principle of least surprise (as the name of your method is printNumbers (but doesn't print numbers and returns the address of the array), then it it is a good idea to refactor your code so that your function printNumbers prints the numbers (and doesn't return the address of the array).

And, given that arrays do have a built in sense of dimension in them (i.e. they are not aware of their own dimensionality, it would be better as others have suggested to use a std::vector instead as this is safer, cleans up after itself, and has a lot more functionality/benefits over C-Style arrays with similar performance.

Upvotes: 1

Yerkezhan
Yerkezhan

Reputation: 481

You can make your arrayOne public and printNumbers() void. Then in main.cpp do the following: 1) execute function printNum.printNumbers() 2) assign to the p your printNum.arrayOne. Hope this helps!

Upvotes: 0

Related Questions