Simple Array Question - Help

A

Ali

Hi,

I want to create an array, whose size should be entered by the user,
instead of me hardcoding it on the code.

The following is what i want to do:

#include <iostream.h>

int main()
{
int numElements=0;
cin>>numElements;

int Array[numElements];

//do something

return 0;
}

The compiler gives an error asking for a constant, such as int
Array[5], etc.

How do i solve the problem, if i want to let the user choose the Array
Size?

Thanks,

Ali
 
I

Ioannis Vranos

Ali said:
Hi,

I want to create an array, whose size should be entered by the user,
instead of me hardcoding it on the code.

The following is what i want to do:

#include <iostream.h>


#include <iostream>

Not needed in the code below.



int main()
{
int numElements=0;
cin>>numElements;

int Array[numElements];


int *Array=new int[numElements];





//do something


delete[] Array;


Or better use std::vector.






Regards,

Ioannis Vranos

http://www23.brinkster.com/noicys
 
V

Victor Bazarov

Ali said:
I want to create an array, whose size should be entered by the user,
instead of me hardcoding it on the code.

The following is what i want to do:

#include <iostream.h>

int main()
{
int numElements=0;
cin>>numElements;

int Array[numElements];

//do something

return 0;
}

The compiler gives an error asking for a constant, such as int
Array[5], etc.

How do i solve the problem, if i want to let the user choose the Array
Size?

You would have to create the array dynamically. Read your favourite C++
book on 'new[]' and 'delete[]'.

Victor
 
J

Jon Bell

The following is what i want to do:

#include <iostream.h>

int main()
{
int numElements=0;
cin>>numElements;

int Array[numElements];

//do something

return 0;
}

Use a vector instead.

#include <iostream>
#include <vector>

using namespace std;

int main ()
{
int numElements = 0;
cin >> numElements;

vector<int> Array[numElements];

// do something

return 0;
}
 
J

Jon Bell

The following is what i want to do:

#include <iostream.h>

int main()
{
int numElements=0;
cin>>numElements;

int Array[numElements];

//do something

return 0;
}

Use a vector instead.

#include <iostream>
#include <vector>

using namespace std;

int main ()
{
int numElements = 0;
cin >> numElements;

vector<int> Array(numElements); // note parentheses not brackets

// do something

return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top