Creating Arrays with user inputed index and elements

Jul 24, 2018 at 10:20pm
First time running an array with user input.

want user to define the maximum number of array elements within 1 - 50.


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
38
39
40
41
42
#include <iostream>
using namespace std;

int inputArraySize(int);

int *ptr1;

int inArraySize;
int userinput;

int main()
{
	cout << "Please provide the number of integer elements between 0 and 50: " << endl;
	cin >> inArraySize;
	inputArraySize(inArraySize);
	ptr1 = new int(inArraySize);
	if (ptr1 == NULL)
	{
		cout << "Error Allocating Memory!" << endl;
		return -1;
	}
	cout << "Enter the integer elements that will be searchable below: " << endl;
	for (int count = 0; count < inArraySize; count++)
	{
		cout << "Integer Element " << (count + 1) << ": " << endl;
		cin >> ptr1(count);
	}

	return 0;
}

int inputArraySize(int num1)
{
	if (num1 <= 0 || num1 > 50)
	{
		cout << "Number of integer Elements must be between 0 and 50." << endl << "Please input another maximum element number between 0 and 50: " << endl;
		cin >> num1;
		inputArraySize(num1);
	}
		
}
Last edited on Jul 24, 2018 at 11:28pm
Jul 25, 2018 at 2:54pm
1) In C and C++, function arguments are passed by value. The num1 inside inputArraySize() is a copy of the value you pass in. If you change the value inside the function, it doesn't change the value in the calling code.

You need to (a) pass the argument as a reference to the variable in the calling code, or (b) return the value from the function.

2) Also, you really shouldn't be using global variables. It's a bad habit, that will lead to problems when you write bigger programs.

3) Is there any particular reason you're calling inputArraySize() recursively? I don't see any need for it here.
Topic archived. No new replies allowed.