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;
}
Related
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];
#include <iostream>
using std::cout;
using std::cin;
void printArray(int A[], int size) {
for(int i = 0; i < size; i++) {
cout << A[i] << "\t";
}
cout << "\n";
}
struct Array {
int *A;
int size;
int length;
};
void display(Array *arr) {
for(int i = 0; i < arr->length; i++) {
cout << arr->A[i] << "\t";
}
cout << "\n";
}
void fillArray(Array *arr) {
for(int i = 0; i < arr->length; i++) {
cin >> arr->A[i];
}
}
void add(Array *arr, int x) {
if(arr->length < arr->size) {
arr->A[++arr->length] = x;
}
}
int main() {
Array arr;
cout << "arr.size before initializing: " << arr.size << "\n"; // gives a garbage value
cout << "Enter the size of the array: ";
cin >> arr.size;
cout << "Output of arr variable &arr: " << &arr << "\n";
arr.A = new int[arr.size];
cout << "arr.length before initializing: " << arr.length << "\n"; // gives garbage value
cout << "How many elements do you want to enter: ";
cin >> arr.length;
fillArray(&arr); //This is not pass by value but pass by reference because
display(&arr); // this function displays the values of arr
add(&arr, 15);
cout << "The length of the array after adding: " << arr.length << "\n";
display(&arr);
printArray(arr.A, arr.length);
}
The output of this program is like this:
$ ./array_adt
arr.size before initializing: -140717888
Enter the size of the array: 10
Output of arr variable &arr: 0x7ffe4e0ec040
arr.length before initializing: 21932
How many elements do you want to enter: 5
4 6 7 3 2
4 6 7 3 2
The length of the array after adding: 6
4 6 7 3 2 0
4 6 7 3 2 0
I am highly confused why the element 15 isn't added to the array of the struct (which is actually a pointer which is initialised to an array in the heap). If someone can throw light on this it would be great for a many people as well as for understanding c++ concepts in depth.
Thanks a lot.
arr->A[++arr->length] = x;
should be
arr->A[arr->length++] = x;
Array indexes start at zero in C++, so the first element past the end of an array arr of size N is arr[N]. In other words 15 did get added to the array, just not in the right place.
Also your code leaks memory because the array allocated in main is never deleted. Correctly allocating dynamic memory is a big (and very important) topic. Consult your favourite C++ book, in particular you should research the rule of three
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);
I built a program that accepts two input from the user, using a array inside a loop, it is passed to a function inside a class which will display the two number.
The problem is when the user is inputting a number and it is 1. The program continuously asks the user to input a number, and when 2 is entered the program ask another number and end, but for example you entered 2 and 3. . . it will then output 2 and 4 (so 3 + 1 ) and always the last number is plus one. Here is the code:
main.cpp:
#include <iostream>
#include "newclass.h"
using namespace std;
int main()
{
int array_variable_main[2];
for(int counter = 1; counter <= 2; counter=counter+1)
{
cout << "Enter a Number: " << endl;
cin >> array_variable_main[counter];
}
newclass sum_object;
sum_object.loop_function(array_variable_main, 2);
return 0;
}
newclass.cpp:
#include "newclass.h"
#include <iostream>
using namespace std;
newclass::newclass()
{
}
void newclass::loop_function(int array_variable[], int arraysize)
{
cout << "The numbers that are stored in the array are: " << endl;
for(int counter = 1; counter <= arraysize; counter = counter+1)
{
cout << array_variable[counter] << endl;
}
}
newclass.h:
#ifndef NEWCLASS_H
#define NEWCLASS_H
class newclass
{
public:
newclass();
void loop_function(int array_variable[], int arraysize);
};
#endif // NEWCLASS_H
You have to remember that array indices go from zero to size-1. So for your array it's zero and one. Anything beyond that leads to undefined behavior. Undefined behavior can't easily be predicted, so the result of your program could be anything.
In C and C++ array index normally starts at 0 so this
int array_variable_main[2];
for(int counter = 1; counter <= 2; counter=counter+1)
{
cout << "Enter a Number: " << endl;
cin >> array_variable_main[counter];
}
will access outside the array
do instead
int array_variable_main[2];
for(int counter = 0; counter < 2; ++counter)
{
cout << "Enter a Number: " << endl;
cin >> array_variable_main[counter];
}