User defined size of array - c++

I want to initialize an array with user defined size, but what know is- I've to declare an array of maximum size and then work on number of elements given by user in this process huge memory wastes. Is there any way to declare an array of size given by user.
I did this but compiler showed error.
int a=0;
std::cout<<"Enter size of array";
std::cin>>a;
const int b=a;
int ary[b];
I'm using Turbo C++IDE

The issue with your code is that you are declaring what is called a variable length array which is not part of C++ (though it is valid C code). See this for an explanation as to why.
You can achieve what you are trying to do in a few different ways though:
You could dynamically allocate an array using a user provided size:
#include <iostream>
#include <memory>
int main(int argc, char** argv)
{
std::size_t a =0;
std::cout<<"Enter size of array";
std::cin>>a;
std::unique_ptr<int[]> arr(new int[a]);
//do something with arr
//the unique ptr will delete the memory when it goes out of scope
}
This approach will work but may not always be ideal, especially in situations where the size of the array may need to change frequently. In that case I would recommend using a std::vector:
#include <iostream>
#include <vector>
int main(int argc, char** argv)
{
std::size_t a =0;
std::cout<<"Enter size of array";
std::cin>>a;
std::vector<int> arr(a);//arr will have a starting size of a
//use arr for something
//all of the memory is managed internally by the vector
}
You can find the reference page here.

You can use new keyword while declaring a dynamic array
int main()
{
int array_size;
std::cin >> array_size;
int *my_array = new int[array_size];
delete [] my_array;
return 0;
}
You should delete the array allocated with new.
You can also use vector for dynamic allocation of memory in c++. Read here for examples on vector

Related

How to make the array size correct in C++?

I'm trying to create an array and the size of the array depends on the user input. But there is an error in my code, It said: "expression must have a constant value".
Here is my code:
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int var;
cout << "What size do you want to choose: "<< endl;
cin >> var;
int arr[var];
}
How can I change my code and make it work?
How can I change my code and make it work?
Change
int arr[var];
to
std::vector<int> arr(var);
This will require #include <vector>
The syntax you are using is known as a "variable length array", and is NON-STANDARD. Only a few compilers support it as an vendor-specific extension to the C++ language.
A standard compliant fixed-length array must have its size known to the compiler as a compile-time constant.
For what you want, you need to use the new[] operator instead:
int *arr = new int[var];
...
delete[] arr;
Or better, use a std::vector container:
#include <vector>
std::vector<int> arr(var);
To allocate an array dynamically, we use the array form of new and delete (often called new[] and delete[]):
#include <iostream>
int main()
{
std::cout << "Enter a positive integer: ";
int length{};
std::cin >> length;
int *array{ new int[length]{} }; // use array new. Note that length does not need to be constant!
std::cout << "I just allocated an array of integers of length " << length << '\n';
array[0] = 5; // set element 0 to value 5
delete[] array; // use array delete to deallocate array
// we don't need to set array to nullptr/0 here because it's going to go out of scope immediately after this anyway
return 0;
}
Arrays in C++ must have constant size known at compile-time. You can preallocate several constant sizes known at compile time and offer the user to choose one of them. Alternatively, you can use another data structure that allows dynamic size allocation e.g std::vector.
Good luck!

Error when trying to print out array in a loop using cout

#include <cstdio>
#include <iostream>
int main (){
int n;
std::cin>>n;
int*a;
for (int i=0;i<n;i++){
std::cin>>a[i];
}
for(int i=0;i<n;i++){
std::cout<<a[i];
}
return 0;
}
I just started working on a problem and I wanted to check if I knew how to read and array and make a sample output array. When I include the second loop program crashes as soon as I enter n and the first number With the following message
3 1
Process returned -1073741819 (0xC0000005) execution time : 4.943 s
Press any key to continue.
int *a; is a pointer to an integer, it is just a pointer to some memory, it has no memory allocated on its own. Since you are dereferencing this pointer a[i] without setting it up first, your compiler should even give you some warning telling that you are using a variable that has not been initialized.
0xC0000005 error code in Windows means access violation. In this case, you are trying to write to some memory which you don't have access to.
You need to allocate memory before you can read or write to it.
If you know beforehand how many entries you will have, you can do static memory allocation, if you don't, then you need to do dynamic memory allocation.
For instance, if you knew that you would need only 20 entries at max, you could easily swap int *a; for int a[20];.
But since you are only getting to know how many entries there will be when the program runs, then you need to go for dynamic memory allocation: int *a = new int[n];.
So your code should be
#include <cstdio>
#include <iostream>
int main (){
int n;
std::cin>>n;
int *a = new int[n];
for (int i=0;i<n;i++){
std::cin>>a[i];
}
for(int i=0;i<n;i++){
std::cout<<a[i];
}
delete[] a; // Release allocated memory.
return 0;
}
You need to allocate memory for a, otherwise the behaviour of the program is undefined. Writing
int* a = new int[n];
would to it, followed by delete[] a; when you're all done (put this just before return 0;).
Alternatively, use a std::vector<int> a(n); and all the memory allocation will be taken care of for you.
Try : int a[20]; rather than int *a;
Your a doesn't point to any valid memory, resulting in undefined behaviour.
What you need is an std::vector :
#include <vector>
int n;
std::cin>>n;
std::vector<int> numbers;
for (int i=0;i<n;i++){
int val;
std::cin>>val;
numbers.push_back(val);
}
for(int i=0;i<n /* or numbers.size()*/ ;i++){
std::cout<< numbers[i];
}
This takes care of dynamic allocation for you so that you don't have to do the dirty stuff yourself.
There are a few issues with your code. Primarily, you request the number 'n' then need to allocate enough space to store that many integers.
The best way to do that is to use vector. You can create this with:
std::vector< int > numbers( n );
You can also create it allocating the memory but waiting until you have data:
std::vector< int > numbers;
numbers.reserve( n );
You also should probably validate your input, for example your input stream (cin) will be invalid if the user enters something that is not an integer, and the original 'n' should be positive if you are going to try to create a vector of that size, and you may need to set a limit or you will suffer a bad_alloc. If you do not mind suffering a bad_alloc you should catch that exception and print an error such as "There is insufficient space to allocate as many numbers".
Of course if you enter a high number like 10 million, you may find the compiler is able to allocate that many but your user will get bored in your loop when you ask him to enter integers 10 million times.
You do not need <cstdio> as a header. You will need <vector> and <iostream>.
int* is a pointer to int, not an array.
To create an array of int, example: int a[100]; - where 100 is the size
Moreover, you should use a std::vector<int> instead:
vector<int> vec;
for (int i = 0; i != n; ++i) {
int temp;
cin >> temp;
vec.emplace_back(temp);
}

Array size declarator, can they be calculated? VC++

Ubernoob question:
Is it possible in MS Visual C++ to declare an array size based upon user input?
int userNum;
cin >> userNum;
const int SIZE = userNum;
int myArray[SIZE];
It seems that if I use a variable in any way to initialize the constant SIZE, that VC++ no longer sees it as a constant for the purposes of setting the array size.
Is there a way around this?
This can be done usign a std::vector
#include <iostream>
#include <vector>
int main() {
int userNum;
std::cin >> userNum;
std::vector<int> myArray(userNum);
myArray[1]=42;
return 0;
}
Note this example has no checks for the size the user has entered.
Using C-style arrays is a bad idea.
Prefer std::vector.
std::vector<int> vec(5); // Vector of 5 ints
No way ;-), you have to allocate the memory dynamically. There are many ways to do that (I'm proposing 3 different solutions here):
int userNum;
cin >> userNum;
const int SIZE = userNum;
int* myArray1 = new int[SIZE];
int* myArray2 = (int*) malloc( sizeof(int) * SIZE ); // not 100% sure about the syntax
// or, better, because memory will be released automatically for you:
std::vector<int> myArray3( SIZE ); // Thank you crashmstr for the comment
And later, when you are done, you'll have to release it:
delete [] myArray1;
free( myArray2 );
// no need to free myArray3
// Note that statically allocated memory (int myArray[SIZE]) is automatically released
myArray[SIZE] is a static allocation done at compilation time, it cannot be controlled by a user input (except if the user is the programmer....who can change the size before the program is actually compiled ;-)
Proposed solution are using dynamic allocation done at runtime, it can be controlled by a user input.
Above mentioned answers about std::vector are absolutely correct.
But if you want to resize the your vector based on user input, you can do:
#include <vector>
std::vector<int> vec;
std::cin >> userSize;
vec.resize(userSize);

Define Global variables from File input C++

I have to define a global array in my C++ code the size of which has to be read from a file. I am using the below code
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
string inputfile = "input.txt";
ifstream infile(inputfile.c_str());
infile>>N; // N = size of Array
int array[N];
// ------some code here-----
int main(){
int N;
cout << N<<endl;
return 0;
}
But if I place the 3 lines
string inputfile = "input.txt";
ifstream infile(inputfile.c_str());
infile>>N; // N = size of Array
inside the main loop this code works. Unfortunately I cant put it inside any function because I need to initialise a global array from variable N.
I have asked many people and searched different places but I cant seem to be able to figure this out. Thanks for your help.
The size of an array has to be a constant expression, i.e. known at compile-time.
Reading a value from a file is an inherently dynamic operation, that happens at run-time.
One option is to use dynamic allocation:
int array_size()
{
int n;
ifstream infile("input.txt");
if (infile>>n)
return n;
else
throw std::runtime_error("Cannot read size from file");
}
int* array = new int[array_size()];
However it would be better to replace the array with std::vector<int> which can be resized dynamically.
Use a global pointer. Define
int* array;
in the global space before your main procedure. Then later, in a loop or not, say
array = new int[N];
to allocate your array. Just remember to also say
delete[] array;
before you exit your main or re-allocate array
int array[N]; - N should be know at compile-time.
Instead, use int array[]=new int[N]; /*some code using array*/ delete[] array;
int *array;
int main(){
ifstream infile("input.txt");
unsigned N;
infile>>N;
array=new int[N];
//using array...
delete[] array; //when no longer needed.
//don't use array after this line
//unless it's array=new int[] instruction
//or you know what you're doing.
}

change global variables in c++

Is there a way to define a global variable by user input?
Lets say I use
#include...
#define N 12
double array[N][N];
void main();...
But I would like the user to be able to choose what N is.
Do I have to have N as a local variable or is there a way around this(without macros)?
I've a pretty small program but with a lot of different variables that need the N value.
Alternatively,
is there a way I could send a group of variables into a function without having to explicitly write them out every time.
for example
myfunction(var1,var2,var3...)
and instead write something like
myfunction(Allvariables)
Thanks a lot for Your answers!
This is a great forum.
int* data;
int main()
{
int n;
// get n from the user.
data = new int[n];
// use data.
.
.
delete[] data;
}
or just forget pointers for ever and use vector!
std::vector<int> data;
data.push_back(55);
// just push_back data!
=======================================================================
EDIT ::
If you want to use Edouard A. way :)
#include <iostream>
#include <sstream>
#include <vector>
int main(int argc, char* argv[])
{
std::vector<double>::size_type dataSize = 0;
std::stringstream convertor(argv[1]);
{
if(argc > 1)
{
convertor >> dataSize;
if(convertor.fail() == true)
{
// do whatever you want here in case
// the user didn't input a number.
}
}
}
std::vector<double> data(dataSize);
// use the vector here.
return 0;
}
I prefere to use lexical_cast in this case, but I am not sure if you have Boost.
#include <iostream>
#include <vector>
#include <boost/lexical_cast.hpp>
int main(int argc, char* argv[])
{
typedef std::vector<double>::size_type vectorSize;
if(argc < 2)
{
// err! The user didn't input anything.
}
vectorSize dataSize = boost::lexical_cast<vectorSize>(argv[1]);
std::vector<double> data(dataSize);
// use the vector here.
return 0;
}
1/ Yes but you need dynamic memory allocation. The program parameters are passed as argc and argv to the main function
int main(int argc, char **argv)
argc is the number of parameters
argv is the array of null terminated strings representing these arguments
argv[0] is the program itself.
2/You can either use variadic function va_start & the like, or functions overriding, or group your data in a structure and pass that to the function
No, that can't be done this way. You need to use dynamic (runtime) memory allocation (new[]). To perform static (compile-time) memory allocation the compiler needs to know the memory block size at compile time.
I'm not really sure what you're trying to do with myFunction but it sounds like you want to look at either creating a struct or pass a std::vector
Make a class (or struct) AllVariables and pass that in.
You don't say whether you want N defined at run time or compile time. If you want it defined at compile time, you can define N as a compiler command line arguement.