One dimension dynamic array

I need to create a main function with a one dimension dynamic array with float data type. The total number of array elements must be controlled by a user input from the keyboard. Test data is three different lengths 3,6,9 of the array. The lengths have to be set up at run time from users input. I understand how to create dynamic array but not where the user inputs the length of the array. How would I implement this?
You could use the command line inputs:
 
int main(int argc, char **argv)

argc is the number of parameters on the command line (including the program name itself). argv contains the parameters themselves, so argv[0] is the program name, argv[1] is the first parameter etc.

You could use atoi() to convert the string to a number.

Alternatively, if the input comes after the user starts the program then you'll need to use some IO. Look at some other threads to see how this is done.

To create a dynamic array of 5 ints, you'd say:
int *arr = new int[5];

I
To clarify dhayden's second code example, they mean to say:
1
2
3
4
5
6
7
8
9
10
11
//Code code code
int ArrSize = 0;

std::cout << "Enter Size Of Array\n";
std::cin >> ArrSize;

//Probably A Good Idea To Check The Users Input Here

float* arr = new float[ArrSize];

//Code code code 


EDIT:Sorry I used the wrong data type.
Last edited on
you could use pointers to do that, read the user input in an int variable, and use a float pointer with a dynamic array:

1
2
3
4
5
int arraySize = 0;
float *array = null;

read user input in to arraySize then
array = new float[arraySize];


then you can use a for-loop to assign values to every position in the array
Think I got it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>
using namespace std;

int main()

{
	int length = 0;
	cout<< "Enter length of array: ";
	cin >> length;

	float* arrsize = new float[length];

	for(int i=0;i < length;i++)
	{
		arrsize[i] = i*i;
		cout<< arrsize[i] << endl;
	}

	delete [] arrsize; // deallocate of array
	system("pause");
} //end of main() 


How do I know if the array has been deallocated?
It has been deallocated because you have called delete[] on line 20. There is no way to programmatically check whether you have remembered to do that however.

You may want to consider std::array if you like.
@Zhuge
Okay, Thanks.
I just wanted to know I if it was some type of code that I could input to check it.
Topic archived. No new replies allowed.