returning values from a function using pointers.

Hello everyone I am new to C++ especially pointers so I need some help with them. I want to print 15 multiples of any integer entered by the user and I know that a function can return only a single value so I used pointers but I just started using them so I am having some trouble. Below is my code which is not working properly it is giving me a memory address during output. So can you help and tell me that what am I doing wrong?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
  #include <iostream>
using namespace std;

class Multiples {
	
	public:
		int *printMultiples ( int userValue ) {
			int arr[15];
			for ( int i = 1; i < 16; i++ ) {
				arr[i-1] = i*userValue;
				}
				int *ret = arr;
			return ret;
			
		}
};

int main () {
	
	int userValue;
	int arr[15];
	Multiples mul;
	int *ptr = mul.printMultiples( userValue );
	cout << "Enter a value : ";
	cin >> userValue;
	
	cout << "The multiples of " << userValue << " are : " << endl;
	cout << ptr << endl;

	
system ("pause");
return 0; 
}
Some errors in your code:
(1) line 12 and 13 are about the array declared in line 8 (not that in line 21). This is an automatic array on the stack which disappears when printMultiples returns. So using it after the call returns is invalid.

(2) userValue has been used (line 23) before it has been initialised (line 25).

(3) line 28 will just print the pointer to the array in line 21, not each of the elements.

You have to get printMultiples to operate on the array on line 21 by passing it in as a parameter, and removing the one on line 8.
thanks for your help ShodanHo and here is the code after correction which is working perfectly.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
using namespace std;

int arr[15];

class Multiples {
	
	public:
		int *printMultiples ( int userValue ) {
			
			for ( int i = 1; i < 16; i++ ) {
				arr[i-1] = i*userValue;
				}
				int *ret = arr;
			return ret;
			
		}
};

int main () {
	
	int userValue;
	int *ptr = NULL;
	Multiples mul;
	
	cout << "Enter a value : ";
	cin >> userValue;
	ptr = mul.printMultiples( userValue );

	cout << "The 15 multiples of " << userValue << " are : " << endl;	
	for (int i = 0; i < 15; i++) 
	cout << userValue << " * " << (i+1) << " : " << ptr[i]<<endl;

	
system ("pause");
return 0; 
}
Last edited on
Topic archived. No new replies allowed.