visual studio also gives these warning. Buffer overrun while writing to 'array1': the writable size is '18' bytes, but '16' bytes might be written. Buffer overrun while writing to 'array2 ': the writable size is '18' bytes, but '16' bytes might be written.
#include <iostream>
#include <string>
using namespace std;
int main()
{
int charCountForA1, charCountForA2;
cout << "How many character do you want for Array 1 ? ";
cin >> charCountForA1;
cout << endl;
cout << "How many character do you want for Array 2 ? ";
cin >> charCountForA2;
//dynamic declaration of memory
double* array1 = new double(charCountForA1);
double* array2 = new double(charCountForA2);
cout << endl;
//to get user inputs to fill the array 1
for (int n = 0; n < charCountForA1; n++) {
double x;
cout << "Enter the element for index " << n << " of Array 1: ";
cin >> x;
array1[n] = x;
}
cout << endl;
//to get user inputs to fill the array 1
for (int n = 0; n < charCountForA2; n++) {
double x;
cout << "Enter the element for index " << n << " of Array 2: ";
cin >> x;
array2[n] = x;
}
The lines
double* array1 = new double(charCountForA1);
double* array2 = new double(charCountForA2);
are not allocating arrays but allocating single double initialized to charCountForA1 and charCountForA2.
Use [] instead of () to allocate arrays.
double* array1 = new double[charCountForA1];
double* array2 = new double[charCountForA2];
Related
I have the following code:
#include <iostream>
using namespace std;
int main()
{
int length = 0;
int arrA[length];
cout << "Enter the length : ";
cin >> length;
cout << "Enter " << length << " integers for array : ";
for(int i = 0; i < length; i++)
{
cin >> arrA[i];
}
cout << "Array A : ";
for(int i = 0; i < length; i++)
{
cout << arrA[i] << " ";
}
cout << endl;
}
The above require the user to input the length of array followed by the integers that will be store in array. It work but the printing of the array value is incorrect when I input length 8 and above.
Working
Enter the length : 7
Enter 7 integers for array : 7 6 5 4 3 2 1
Array A : 7 6 5 4 3 2 1
Not working
Enter the length : 8
Enter 8 integers for array : 8 7 6 5 4 3 2 1
Array A : 8
Could this be due to memory issue or something?
int length = 0;
int arrA[length];
This creates an array of size zero
cout << "Enter the length : ";
cin >> length;
This sets the length variable to a value entered by the user but doesn't change the size of arrA which has already been created.
You obviously think that when the length variable changes that the array arrA will change as well, but this is not true.
Because you are accessing elements of an array which has zero size the behaviour of your program is undefined.
In addition this whole approach is incorrect because
int length;
...
int arrA[length];
is not legal C++. Because length is a variable this is a variable length array or VLA. VLAs are legal in C but are not legal in C++.
The best way to write this code in C++ is to use a vector. A vector is the C++ improvement on a C array.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int length;
cout << "Enter the length : ";
cin >> length;
vector<int> arrA(length);
...
int length = 0;
int arrA[length];
This is not valid C++.
What you may want to do is:
int *arrA = new int[length];
after cin >> length.
You will have to free the pointer later with delete[] arrA;
It is not due to a memory issue. But because variable length arrays are not part of the C++ standard.
length is a variable length array.
Read more about variable length arrays
Here
Here is the code if you do not want to use a vector. I would suggest not to use this for multifarious reasons. But go ahead and knock yourself out.
#include <iostream>
using namespace std;
int main()
{
int length = 0;
int *arrA = new int [length];
cout << "Enter the length : ";
cin >> length;
cout << "Enter " << length << " integers for array : ";
for (int i = 0; i < length; i++)
{
cin >> arrA[i];
}
cout << "Array A : ";
for (int i = 0; i < length; i++)
{
cout << arrA[i] << " ";
}
delete[] arrA;
cout << endl;
return 0;
}
I tried to write this code but it says expression did not evaluate to a constant. I learn that this is because VS does not allow an undeclared array, as "n" is not understood by VS. How can i fix this code with a declared array?
#include<iostream>
using namespace std;
int main()
{
int i, n;
cout << "Enter size of array:";
cin >> n;
int a[n];
cout << "Enter elements of array:" << endl;
for (i = 0; i < n; i++)
cin >> a[(i + n - 1) % n];
cout << "Result after left shift:" << endl;
for (i = 0; i < n; i++)
cout << a[i] << " ";
cout << endl;
return 0;
}
How can i fix this code with a declared array?
Option 1
Declare the array with sufficiently large size and make sure that n is less than or equal to the size before using the array.
int i, n;
int a[1000];
cout << "Enter size of array (less than or equal to 1000):";
cin >> n;
if ( n > 1000 )
{
// Deal with the problem.
}
else
{
// Use the array.
}
Option 2
Use std::vector.
int i, n;
cout << "Enter size of array:";
cin >> n;
std::vector<int> a(n);
Variable length arrays (VLAs) are not part of the C++ language, although some compilers (like g++) support them as an extension.
You should be using the std::vector container from the Standard Template Library, instead. Once declared and properly initialized, a std::vector can be used much like a plain array:
#include<iostream>
#include <vector>
using std::cout; using std::cin; using std::endl;
int main()
{
int i, n;
cout << "Enter size of array:";
cin >> n;
std::vector<int> a(n);
cout << "Enter elements of array:" << endl;
for (i = 0; i < n; i++)
cin >> a[(i + n - 1) % n];
cout << "Result after left shift:" << endl;
for (i = 0; i < n; i++)
cout << a[i] << " ";
cout << endl;
return 0;
}
You have to allocate the array on the heap like this:
int* a = new int[n];
But when you do heap allocations, always remember to delete the allocated memory after you are done using it:
delete[] a;
If you don't want to worry about deleting the memory, you can look into std::vector.
so i have been trying to get the input of array's size and its elements then display the elements to the screen but when i for example put
array's size : 7
array's elements : 1 2 3 4 5 6 7
output is:
1
2
3
4
5
6
6
The code :
#include <iostream>
using namespace std;
int main () {
int n , Arr[n];
cout << "please put the size of the array " ;
cin >> n;
cout << "please enter array's elemets ";
for (int k=0; k<n ; k++) {
cin >> Arr[k];
}
for (int i=0;i<n;i++){
cout << Arr[i] << endl;
}
}
int Arr[n] where n is not a compile time constant is illegal C++ code. Some compilers allow it as an extension (Variable Length Array).
Even with VLA extension, the code is invalid because n is uninitialized when used in your code.
First the real solution:
Use std::vector (tadaaa):
#include <iostream>
#include <vector>
int main () {
int n;
std::vector<int> arr;
std::cout << "please put the size of the array " ;
std::cin >> n;
arr.reserve(n); // optional
std::cout << "please enter array's elemets ";
for (int k=0; k<n ; k++) {
int elem;
std::cin >> elem;
arr.push_back(elem);
}
for (auto e : arr) {
std::cout << e << std::endl;
}
}
If you need to compile against C++98 (wow):
for (std::vector<int>::iterator it = arr.begin(); it != arr.end(); ++it) {
std::cout << *it << std::endl;
}
or just:
for (std::size_t i = 0; i < arr.size(); ++i) {
std::cout << arr[i] << std::endl;
}
If you insist on using VLA (I recommend against it):
int n;
cout << "please put the size of the array " ;
cin >> n;
int Arr[n];
cout << "please enter array's elemets ";
for (int k=0; k<n ; k++) {
cin >> Arr[k];
}
for (int i=0;i<n;i++){
cout << Arr[i] << endl;
}
As many others have mentioned in the comment section, another way (in case you want to stick with C array) would be to allocate the array dynamically on the heap.
#include <iostream>
using namespace std;
int main () {
int n;
cout << "please put the size of the array " ;
cin >> n;
int* Arr = new int[n]; //dynamically allocate an array to hold n int on the heap
cout << "please enter array's elemets ";
for (int k=0; k<n ; k++) {
cin >> Arr[k];
}
for (int i=0;i<n;i++){
cout << Arr[i] << endl;
}
delete [] Arr; //make sure to clean up the heap memories
}
From dcl.init#12:
If no initializer is specified for an object, the object is
default-initialized. When storage for an object with automatic or
dynamic storage duration is obtained, the object has an indeterminate
value, and if no initialization is performed for the object, that
object retains an indeterminate value until that value is replaced
([expr.ass]).
unsigned char c;
unsigned char d = c; // OK, d has an indeterminate value
int e = d; // undefined behavior
Thus, in your code:
int n , Arr[n];
n has an indeterminate value until it's assigned in cin >> n;
using n with this indeterminate value (not value-/zero-/default-initialized and not assigned), can lead to undefined behavior.
Ok so here's my code. I'm getting no errors in the compiler, however when I run this program it lets me input 2 names then crashes with a Window's Error. What in the heck am I doing wrong?!
#include <iostream>
using namespace std;
//declaration of variables
int i; // Loop Counter
int x; // Number of Family Members
int main()
{
string FamilyName[x]; // Array of Names
cout << "Enter Number of Family Members" <<endl;
cin >> x;
for (i = 0 ; i < x ; i++){
cout << "Enter Family Member's Name: " <<endl;
cin >> FamilyName[i];
}
for (i = 0 ; i < x ; i++){
cout << FamilyName[i] <<endl;
}
return 0;
}
You can solve the problem in two ways, allocate the array to a large size(x should be initialized...and it should be a constant value) and then the code becomes:
#include <iostream>
#include <string>
using namespace std;
//declaration of variables
int i; // Loop Counter
const int x = 500; // MAX Number of Family Members
int main()
{
string FamilyName[x]; // Array of Names
int count;
cout << "Enter Number of Family Members" <<endl;
cin >> count;
for (i = 0 ; i < count ; i++){
cout << "Enter Family Member's Name: " <<endl;
cin >> FamilyName[i];
}
for (i = 0 ; i < count ; i++){
cout << FamilyName[i] <<endl;
}
return 0;
}
Or use dynamic memory allocation to read the number of family member first and then do the allocation:
int main()
{
int count;
cout << "Enter Number of Family Members" <<endl;
cin >> count;
auto FamilyName = new string[count];
for (i = 0 ; i < count ; i++){
cout << "Enter Family Member's Name: " <<endl;
cin >> FamilyName[i];
}
for (i = 0 ; i < count ; i++){
cout << FamilyName[i] <<endl;
delete[] FamilyName;
}
Hope this helps
You are not allocating any memory to your string array, on this line string FamilyName[x]; // Array of Names x is not defined. It also may be a good idea to set a max array size or have some way of pushing on to the end of the array.
The size of your array should be constant.
Maybe use a vector of strings since vectors can grow dynamically.
string name;
vector<string> FamilyName;
for(int i = 0; i < x; i++)
{
cin >> name;
FamilyName.push_back(name);
}
Either that or give your array a constant size larger than any family size you might encounter.
string FamilyName[100];
if you wouldn't ever get a family with over 100 members.
You need to either allocate reasonable memory for FamilyName or use STL:
string[] FamilyName;
//after get x
FamilyName = new string[x];
or
vector<string> FamilyName;
cin << temp_string;
FamilyName.push_back(temp_string);
Trying to use basic pointer feature to display some numbers that entered by user. However, the displaying is in error while the input is OK.
#include <iostream>
using namespace std;
int main()
{
cout << "How many integers you wish to enter? ";
int InputNums = 0;
cin >> InputNums;
int* pNumbers = new int [InputNums]; // allocate requested integers
int* pCopy = pNumbers;
cout<<"Successfully allocated memory for "<<InputNums<< " integers"<<endl;
for(int Index = 0; Index < InputNums; ++Index)
{
cout << "Enter number "<< Index << ": ";
cin >> *(pNumbers++);
}
cout << "Displaying all numbers input: " << endl;
for(int Index = 0, int* pCopy = pNumbers; Index < InputNums; ++Index)
cout << *(pCopy++) << " ";
cout << endl;
// done with using the pointer? release memory
delete[] pNumbers;
return 0;
}
Error from the line for(int Index = 0, int* pCopy = pNumbers; Index < InputNums; ++Index).
The code actually from textbook "teaching c++ in 21 days", nothing changed.
Please help, thanks a lot.
The example in your book is bad. It should be like this (the code also bad, but here is the code should be):
#include <iostream>
using namespace std;
int main()
{
cout << "How many integers you wish to enter? ";
int InputNums = 0;
cin >> InputNums;
int* pNumbers = new int [InputNums]; // allocate requested integers
int* pCopy = pNumbers;
cout<<"Successfully allocated memory for "<<InputNums<< " integers"<<endl;
for(int Index = 0; Index < InputNums; ++Index)
{
cout << "Enter number "<< Index << ": ";
cin >> *(pCopy++); //use pCopy to 'walk' the array
}
cout << "Displaying all numbers input: " << endl;
pCopy = pNumber; //reset pCopy
for(int Index = 0; Index < InputNums; ++Index)
cout << *(pCopy++) << " ";
cout << endl;
// done with using the pointer? release memory
delete[] pNumbers; //pNumbers must still point to the address returned in line 10
return 0;
}
I wonder who is the author of the book.
Change cin >> *(pNumbers++); to cin >> *(pCopy++);
Change int* pCopy = pNumbers to *pCopy = pNumbers
That should do the trick. However, this example is ugly as hell. I would recommend you changing your textbook.