I try to create an array. The size of it depends on the user's input. But how can I do it? or should I use string or vector instead?
I am new to C++. When I googled the problem, I still didn't get it. I tried the following code but it was not working.
const int t;
cin >>t;
double myarrary[t]={};
but my friends code works.
cin >> num;
int px[num]={};
Thank you
Variable length arrays like double myarrary[t] where t is a run-time value are a C feature. It is not in C++ standard, but some compilers do support that.
Use std::vector for portability.
Related
So simple code like:
int n;
cin >> n;
int s[n], p[2*(n-1)][3];
I have to translate to:
int n;
cin >> n;
vector<int> s(n, 0);
vector<vector<int>> p(2 * (n - 1), vector<int>(3));
I would like to see something like:
int n;
cin >> n;
mat s(n), p(2*(n-1), 3);
I definitely do not want to use new\make_unique and std::array+std::vector mix for such simple stuff. Two lines are an ugly mess IMHO so I seeek for a way to keep C like sintax.
So what is a workaround? Any define/standard header/copy-pastable STL based C++ type?
Variable length arrays are not supported by standard C++.
std::vector<int> is the idiomatic way of implementing a contiguous block of int data whose size is not known at compile time. A good rule of thumb is to use std::vector until you find a compelling reason not to.
Variable length arrays (i.e. arrays where at least one dimension is not a compile time constant) are not supported in standard C++. Hence, you cannot write something like cin >> n; int s[n].
Some extensions exist, but still - for very large values of n, you might get troubles if the compiler at hand puts such an array on the "stack", which is usually more limited than the heap.
The standard way is to use std::vector<int> s(n) or, if - though usually not recommended - for some reason you want a "plain" array not wrapped by an object, you could write int *s = new int[n];, although it is then incumbent on you calling delete[] s; when you no longer need the array.
alloca is another alternative. Not standard but widely supported.
By standard C++, there's no Variable Length Arrays (VLAs). Either use an STL like std::vector, or define the variables as const (that you can't modify at runtime).
I'm attempting the Latin Square Daily Challenge on Reddit and I wanted to use an array which allocates size during run-time by using the following code:
int n;
cout << "Please enter the size of the Latin Square: ";
cin >> n;
int latinsquare[n][n];
This works in online compilers but not in Visual Studio 17. Is there a way to do this in the Microsoft C++ compiler?
This is because variable-length arrays are non-standard in C++ (why?). You can allocate latinsquare using new, but an idiomatic way of doing it in C++ is to use a vector of vectors:
std::vector<std::vector<int>> latinsquare(n, std::vector<int>(n, 0));
VLA is not a part of c++ standard. If you want to use them you need compiler extension.
But you may
Create it dynamically via new and delete operators
Use std::vector
My program is this:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
char choice;
int o,i,marks[i],ttlcredit=0;
double ttlGPA=0,finalGPA=0,credit[7][2],clsavg;
cout<<"Please enter what you want to calculate"<<endl;
cout<<"A for calculating Class Average GPA"<<endl;
cout<<"B for calculating a Specific GPA"<<endl;
cout<<"Your choice is? ";
cin>>choice;
cout<<endl;
if (choice == 'A'||choice == 'a')
{
cout<<"=========================================="<<endl;
cout<<" Class Average GPA"<<endl;
cout<<"=========================================="<<endl<<endl;
cout<<"Please enter the number of students in the class: ";
cin>>number;
for(i=0;i<number;i++)
{
cout<<"\nEnter student #"<<i+1<<"'s marks: ";
cin>>marks[i];
ttlGPA=ttlGPA+marks[i];
}
clsavg=ttlGPA/number;
cout<<"\nThe Average is: "<<clsavg<<endl;
}
else
{
}
}
It is half completed. When I build and run on CodeBlocks, an error instantly appeared:
I tried finding the source of error and I think that it is caused by the following in the code:
int o,i,marks[i],ttlcredit=0;
What makes me think so is because when I remove the [i] from marks[i], I will be not receive that error.
I think is stack overflow because I use Microsoft Visual Studio to help me debug and this is the error they gave me:
Unhandled exception at 0x0041419e in Project (1).exe: 0xC00000FD: Stack overflow.
My question is...
Is that the main cause of problem?
How do I resolve this issue?
You have to initialize the marks array with a positive length.
Get the number of students first, THEN create the array using that number.
Also, you need to declare the variable number.
As the other answers stated correctly, the problem is that int i is used uninitialized. However, the proposed fix
// initialze i
int marks[i];
is not standard C++, but only available through a compiler extension. In C++, the length of a built-in array must be a compile time constant. The better solution would be using std::vector:
// initialize i (better make it std::size_t instead of int)
std::vector<int> marks (i);
This will create a variable length array in a safe and standard conforming way.
First thing to say is that you simply shouldn't use arrays. They just are too weird in C and C++, and we have superior alternatives in modern C++.
Anyway, whether you use arrays or vectors, there are some important issues. Before discussing marks[i], it's simpler to look at credit[7][2] in this code.
int o,i,marks[i],ttlcredit=0;
double ttlGPA=0,finalGPA=0,credit[7][2],clsavg;
The dimensions are explicit in this declaration of credit. It's seven-times-two. Simple enough. You can read and write to credit[0][0] and credit[6][1] and many other values. But if you go outside the range, e.g. try to use credit[7][0], your program will compile and will probably appear correct for a while, but it could behave very badly and it is undefined how it will behave. It could decide to delete all the files on your computer, it is (seriously) entitled to do anything random and crazy. This is Undefined Behaviour.
Anyway, the really weird line is the declaration of marks.
int marks[i];
This definitely doesn't do what you think it does. It doesn't create an array that can be "indexed with arbitrary i". No, it allocates an array whose size is the initial value of i. But i is undefined at this stage so this is meaningless.
But i isn't relevant here anyway. How big do you want this array to be? The answer is number, isn't it? That is the number of people you'll store in your array.
So, a small improvement is to do this instead of int marks[i].
int marks[number];
But even this isn't correct. The value of number isn't set until the line cin >> number;, therefore you must declare int marks[number] after the line cin >> number; in order to ensure that marks has the correct size.
But, but, but, even after all this, we still don't have standard C++. It's OK to do int credit[7][2] because the size is fixed at compile time. You are normally not allowed to set the size of an array at runtime, e.g. int marks[number]. You might be able to use it if your compiler allows this extension (it's called Variable Length Array, from C).
So, this is not standard C++, and it's potentially very dangerous (see the Undefined Behaviour). What's the solution?
The solution is the standard solution for any problem involving arrays. Stop using arrays. (Really advanced programmers, in particular situations, might use std::array in modern C++, or even write their own clone of std:: array in older C++. But raw C [] arrays are to be avoided where possible.)
#include<vector>
int o,i,ttlcredit=0;
std::vector<int> marks;
marks is initially empty. We don't do cin >> marks[i];. Instead we use push_back to append new items to the end of the list.
int next_mark;
cin >> next_mark;
marks.push_back(next_mark);
Also, don't use marks[i] with a vector. It might look OK, but it is dangerous. Better to use marks.at(i) to read or write the element. at will do bounds checking for you, giving you a proper error message if i is too small (less then 0) or too big for the size of the vector.
int o,i,marks[i],ttlcredit=0;
i is not initialized. initialize i first.
If you are not sure of the size of the array, allocate it dynamically.
use new
refer this link on how to use new - cpluspluss
I'm passing the array size dynamically through a variable named size, it's working fine in c but not in c++. Please tell me the reason, Thanks in advance.
#include <iostream>
#include <stdlib.h>
using namespace std;
int size;
int main(int argc, char *argv[])
{
int i ;
int *a[size];
cout<<"Enter size";
cin >> size;
for(i =0; i < size ;i++)
{
cout<<"Enter value:" ;
cin>>a[i] ;
}
for(i=0 ; i < size; i++)
{
cout<<a[i]<< " ";
}
system("PAUSE");
return 0;
}
I have executed the same program with proper I/O changes, its executed properly.
Also please help me in understanding how compiler is behaving in this case at the time of array declaration.
Please tell me the reason
The reason is that C++ doesn't have variable-length arrays. Perhaps you are looking for std::vector<int> (likely) or new int (unlikely).
Also please help me in understanding how compiler is behaving in this case at the time of array declaration.
Just like it behaves in any other case: it parses the source text and outputs machine code of which the semantics correspond to that of the source code. It's just that the size of a variable-length array is not hard-coded as a constant, instead it is stored in a register or on the stack (like some sort of "variable"), and size calculations (pointer arithmetic, in particular) are performed agains that stored value.
Your code tries to allocate an amount of memory from an uninitialized variable size. Its value is assigned only later:
int a[size];
/* ... */
cin >> size;
If you switch the order of these statements, it might do what you want, if your C++ compiler has an extension for variable length arrays. A more portable and generally preferable solution would be:
cin >> size;
std::vector<int> a(size);
Edit: You probably want an int[] not *int[].
You cannot create variable length arrays in c++. try using vectors instead
There are no VLAs in C++.
If you want to write your code to be used in a C++ project, then write your code in C++ (use std::vector instead of VLAs) or write your code in C, compile it with a C compiler and use your linker to link to it from your C++ project.
int *a[size]; by this statement you want to create a array of size size , but you have not initialized the variable size.C++ doesn't support variable length array.You can do it by this:
int size;
cin>>size;
int *a[size];
or just use STL vector which allocates memory dynamically.
vector<int>a;
and to put value in the vector just push back the values
a.push_back(56);
For more about vector check out this link
I want to initialize an array with a size using a value I read into an integer variable.
I cant seem to understand why it works in Dev-C++ but not in Turbo C++. Here's the code to help make things clear
int arr_size; //cin max value for lets say number of students or something...
cin >> arr_size;
int array[arr_size]; // declares array with size (assume 10 or 100) with range 0 to 9 or 0-99
The compiler shows an error in Turbo C++ (really old, I know, but my school uses it unfortunately). Dev-C++ and codeblocks doesnt.
Why is that so? I know its bad practice "as they define it in some books" to have an array size the same as an int value, but is there a work around for this in Turbo C++?
I want to know why the error happens and how I can get a work around it ... thanks a lot!
The C++ standard only permits arrays to be sized with a constant expression. (However, some compilers may offer it as a non-standard language extension.)
You could use a std::vector instead:
std::vector<int> array(arr_size);
Or you could dynamically-allocate memory manually:
int *const array = new int[arr_size];
...
delete [] array; // Remember to delete when you're done
Variable length arrays are not allowed in standard c++. You can do it in C99. Consider using C++ std::vector as :
std::vector<int> array(arr_size);
And you can index it exactly like the array if you have to.
The workaround is to dynamically allocate this array, making sure to delete the memory when done.
int arr_size; //cin max value for lets say number of students or something...
cin >> arr_size;
int *arr = new int[arr_size];
//use the array as needed
delete [] arr;
You want variable length array (VLA) which is not allowed in C++. Its allowed in C99.
Use std::vector<int> instead, as:
int arr_size;
cin >> arr_size;
std::vector<int> array(arr_size);