Local Variable being changed without manipulation - c++

I'm creating a simple quick sort program that initializes an empty array and asks the users for inputs to determine how many elements are going to be sorted and what elements are going to be sorted.
The problem I am encountering is a local variable is being changed despite being only being referenced to once assigned. Attached below is the code.
int main()
{
int amount;
int numbersarray[] = {};
std::cout << "How many numbers do you want to sort? " << std::endl;
std::cin >> amount;
for(int i = 0; i <= amount; i++){
std::cout << "Enter number to be sorted: " << std::endl;
std::cin >> numbersarray[i];
}
std::cout <<"Amount to be sorted: " << amount << std::endl;
for(int i = 0; i <= amount; i++){
std::cout << numbersarray[i] << std::endl;
}
}
What I expect to be occurring, when I input the amount as 5, I should be able to input 5 elements into the array, instead however the Amount printed is 2 and the maximum elements I can put into the array is 3.
Below is the execution output.
How many numbers do you want to sort?
5
Enter number to be sorted:
5
Enter number to be sorted:
2
Enter number to be sorted:
5
Amount to be sorted: 2
5
2
5
I've tried messing around with the for statement but I don't think I'm doing it right as it hasn't fixed the problem, The manipulation of the for statement I'm doing is changing the condition (i.e !=, <, <=)

You have undefined behavior. Anything can happen. Local variable can change without reason, the program can crash and your computer can format itself with linux 6.9
There are many problem. The first is that your program is invalid according to the standard:
int numbersarray[] = {};
This is not valid. Array need a size:
constexpr int max_amount = 32;
int numbersarray[max_amount] = {};
If you need it to be dynamic, use vector:
std::vector<int> numbersarray;
numbersarray.resize(amount);
Second, you have another source of undefined behavior:
// Iterates too much, numbersarray[amount] is past the end
// ~~~v~~~~~~~
for(int i = 0; i <= amount; i++){
std::cout << "Enter number to be sorted: " << std::endl;
std::cin >> numbersarray[i];
}
It should be:
for(int i = 0; i < amount; i++){
std::cout << "Enter number to be sorted: " << std::endl;
std::cin >> numbersarray[i];
}
To avoid invalid code and undefined behavior, you should enable warnings.

numbersarray is a C-style array with a size of zero and doesn't adjust its size dynamically (most compilers might even fail to compile int numbersarray[] = {}; since an empty initializer isn't allowed for an array with unspecified size).
Writing or reading its elements causes undefined behaviour (which can be access violations, changing unrelated variables, and much more). This is the reason why you might see the values of local variables changing. Someone else that uses the same code could get completely different behaviour, since it is undefined.

Related

How do I get this C++ code to read five integers from the user instead of one?

I'm taking an elementary programming course where we use C++ and I'm stuck on a couple of assignments. Please excuse my potentially bad terminology going forward. Part of my basic program I'm writting asks "Write down 5 integers: " and then the user gets to pick the integers and a message "You wrote the integers: n1 n2 n3 n4 n5" is returned. There are several of these questions and I'm not allowed to use more then one variable of the same type. The problem is that the user could respond with n1 n2 n3 n4 n5 hello, and hello is supposed to be ignored. How do I accomplish this?
If we for a moment assume that we are only to write down one integer instead of 5, then perhaps something along the lines of the code below would work.
#include <iostream>
using namespace std;
int main()
{
int num;
cout << "Write down an integer: "
<< flush;
cin >> num;
cout << "You wrote the integer: "
<< num
<< endl;
}
But how do I do this with five integers. Further, how do I ignore that extra hello? I'm assming that cin.ignore is to be used here somehow.
If you want to repeat the procedure 5 times, you could just copy-paste it, but that's definitely not a good practice. What's much better is to use a loop/cycle, like for.
You'll also need to store all 5 integers into memory. You could use 5 variables (int n1, n2, n3...), but again, that's not a very good practice and as you state, that's not allowed in your case. Solution is to use an array, which can hold several values of the same type.
Here is a working example with explaining comments:
int nums[5]; // this array will hold 5 integers
int n;
cout << "Write down 5 integers:" << endl;
for (n = 0; n < 5; ++n) { // run code in the braces 5 times
cin >> nums[n]; // store typed integer into nth position of the array
}
cout << "You wrote: ";
for (n = 0; n < 5; ++n) { // run code in the braces 5 times
cout << nums[n] << " "; // print integer at nth position of the array
}
Note: One could say that both nums and n are of the same type, int. In that case, you could extend the array nums to the size of 6 items and use the last one (to which you can refer as nums[5]) as an indexing variable for the loops.

When reversing an array in c++, why do i get a "random" number in between an input and output?

Up until now I've been studying C, and now i wanted to try C++. Started out with some easy tasks. But I can't seem to find the answer, why is there a number either 0 or 488834... printed out.
I've tried re-declaring variables, using
for(n-1; n>=0; n--){
cout << a[n] << endl;
}
int main(){
int var = 0;
int a[100],n;
cin >> n;
for(int i=0; i<n; i++){
cin >> a[i];
var++;
}
for(var-1; var>=0; var--){
cout << a[var] << endl;
}
Everything works, except that 0/some number in the middle of the output
Result
In the following line:
for(var-1; var>=0; var--){
var-1 doesn't actually modify the value of var. So var gets to keep its original value, which means the first value you end up printing is what is after the end of the original sequence.
Use var = var - 1 instead.
In your second for loop you don't have an assignment, just a statement. You start printing from a location of the array that contains an invalid number due to this, you may want too have your second loop read
for(var = var-1; var>=0; var--){
cout << a[var] << endl;
}
Now, there are more element ways to write this, but this is a fix that is needed in your code.

C++ program only lists last value entered into an array

I am trying to output the values present in the array, that are accepted during runtime, onto the console. But when I run this program I get the 5 values in the array as the last value only.
For example: if i give 0 1 2 3 4 as the five values for this program then the output is shown as 4 4 4 4 4.
#include "stdafx.h"
#include<iostream>
using namespace std;
int main()
{
int arrsize = 5;
int *ptr = new int[arrsize];
*ptr = 7;
cout << *ptr << endl;
cout << "enter 5 values:";
for (int i = 0; i < arrsize; i++)
{
cin >> *ptr;
cin.get();
}
cout << "the values in the array are:\n ";
for (int i = 0; i < arrsize; i++)
{
cout << *ptr << " ";
}
delete[] ptr;
cin.get();
return 0;
}
Both of your loops:
for (int i = 0; i < arrsize; i++)
...
loop over a variable i that is never used inside the loop. You are always using *ptr which refers always to the first element of the dynamically allocated array. You should use ptr[i] instead.
A part from that, dynamic allocation is an advanced topic. I'd recommend sticking with simpler and more commonly used things first:
std::cout << "Enter values:";
std::vector<int> array(std::istream_iterator<int>(std::cin), {});
std::cout << "\nThe values in the array are:\n";
std::copy(begin(array), end(array), std::ostream_iterator<int>(std::cout, " "));
Live demo
Following issues I think you could tackle:
The first include can be omitted I think. Your code works without that.
You use cin.get(), not sure why you need that. I think you can remove that. Even the one at the very end. You could put a cout << endl for the last newline. I am using Linux.
And use ptr like an array with index: ptr[i] in the loops as mentioned in the other answer. ptr[i] is equivalent to *(ptr+i). You have to offset it, otherwise you're overwriting the same value (that is why you get that result), because ptr points to the first element of the array.
P.S.: It seems that if you're using Windows (or other systems) you need the cin.get() to avoid the console to close down or so. So maybe you'd need to check it. See comments below.

Code crashes. Trying to remove characters from char array C

I am basically trying to store everything after a certain index in the array.
For example, I want to store a name which is declared as char name[10]. If the user inputs in say 15 characters, it will ignore the first five characters and store the rest in the char array, however, my program crashes.
This is my code
char name[10];
cout<< "Starting position:" << endl;
cin >> startPos;
for(int i= startPos; i< startPos+10; i++)
{
cout << i << endl; // THIS WORKS
cout << i-startPos << endl; // THIS WORKS
name[i-startPos] = name[i]; // THIS CRASHES
}
For example, if my name was McStevesonse, I want the program to just store everything from the 3rd position, so the end result is Stevesonse
I would really appreciate it if someone could help me fix this crash.
Thanks
Suppose i is equal to 3. In the last iteration of the loop, i is now equal to 12, so substituting 12 in for i, your last line reads
name[12-startPos] = name[12];
name[12] is out of bounds of the array. Based on what you have shown so far, there is nothing but garbage stored in name anyway before you start doing this assignment, so all you're doing is reorganizing garbage in the array.
Please in future: post full compilable example.
A simple answer is that your array maybe is out of bound, since you don't provide full example its hard to know exactly.
Here is a working example:
#include <iostream>
using namespace std;
int main() {
int new_length, startPos;
int length = 15;
char name[15]= "McStevesonse";
cout<< "Starting position:" << endl;
cin >> startPos;
if(new_length <1){ // you need to check for negative or zero value!!!
cout << "max starting point is " <<length-1 << endl;
return -1;
}
new_length=length-startPos;
char newname[new_length];
for(int i= 0; i<new_length; i++){
newname[i] = name[i+startPos]; // THIS CRASHES
}
cout << "old name: " << name << " new name: " << newname << endl;
return 0 ;
}
To put it simply, change this:
for(int i= startPos; i< startPos+10; i++)
To this:
for(int i= startPos; i<10; i++)
You should be fine with that.
Explanation:
At some point, when you use the your old loop, this name[i-startPos] = name[i] would eventually reach an array index out of bounds and causes the crash.
Don't forget to clean up/hide the garbage:
Doing so, would cause the output to produce some kind of garbage outputs. If you got a character array of 'ABCDEFGHIJ', and have chosen 3 as the starting position, the array would be arranged to 'DEFGHIJHIJ'. In your output, you should atleast hide the excess characters, or remove by placing \0's

(C++) Specific values in an array

I'm not sure how to title my question, but here goes. I am testing some features, and I have hit a snag.
What I want to know is how can I set up a "for" or "if" statement to only put values in an array that meet a criteria? For example, find every divisor for a number, but only put factors in an array.
Any help would be loved, source code can be provided if needed :). Yes, I am new, so be gentle!
#include <iostream>
using namespace std;
int main(){
int n;
int counter = 1;
cout << "What number would you like to use? ";
cin >> n;
int DiviArray[n];
for (int k=0,j=1;k<n;k++,j++)
{
DiviArray[k] = n-k;
}
int k = 3;
int factn[n];
cout << "Factors of " << n << ": " << endl;
for (int i=0, j=1;i<n;i++,j++)
{
factn[i] = n/DiviArray[i];
if(factn[i]*DiviArray[i]==n)
{
cout << counter << ". " << factn[i] << " x " << DiviArray[i] << endl;
counter++;
}
}
return 0;
}
EDIT: Decided to go with vectors, not sure if I can get it to work, but thanks for the feedback guys :)
Since you don't know in advance how many values will meet the condition, you should use a std::vector.
As a benefit, it keeps track of how many elements you've already added, so push_back will always use the next available index.
This also fixes
cin >> n;
int DiviArray[n];
which isn't legal C++.
If you only want to put the values into the array that match the condition, then you should only put a number into the array when the condition is matched. To do that, the statement that puts a number into the array has to be inside the if-block for the condition. I hope I don't need to explain why :)
This is the only time in your program where you actually do want two indices: one that is incremented every time through the loop (to count how many times to run the process), and one that is incremented only when you put a number in the array (to figure out where the next number goes). Everywhere else, you've created a completely useless j variable (the uselessness should be apparent from the fact that there is no code that actually uses the value, only code to set it).