How to solve a while loop that suddenly terminates itself? - c++

I have code to look for permutations which takes input from the user until the user is satisfied with the amount of input added.
However, when receiving more than 4x input, the code suddenly stuck/terminated itself. I've tried changing the array type to dynamic memory, but the result continues to be the same.
Strangely when I test this code using http://cpp.sh/, it runs normally. I think the problem is with my compiler (I used VS code and MinGW to compile and run it.) What do you think is wrong?
My code is below:
#include <iostream>
#include <string>
using namespace std;
int main() {
int KombAngka;
bool Lanjut = true;
int x = 0;
int *Angka = new int(x);
string YaTidak;
while(Lanjut) {
cout << "Number-" << x + 1 << ": ";
cin >> Angka[x];
LoopYaTidak:
cout << "Are the numbers enough?(y/n)?: ";
cin >> YaTidak;
if (YaTidak == "y") {
Lanjut = false;
}
else if (YaTidak == "n") {
Lanjut = true;
}
else {
cout << "Enter the correct answer!(y/n)" << endl;
goto LoopYaTidak;
}
x++;
}
cout << "All numbers: (";
for (int z = 0; z <= x - 2; z++) {
cout << Angka[z] << ", ";
}
cout << Angka[x - 1] << ")" << endl;
cout << "The number of combinations of numbers used: ";
cin >> KombAngka;
int JumlahAngka = x;
const int StopLoop = JumlahAngka - KombAngka;
for (int i = JumlahAngka - 1; i > StopLoop; i--) {
JumlahAngka = JumlahAngka * i;
}
cout << "The number of queue numbers consisting of " << KombAngka << " different numbers are " << JumlahAngka << endl;
system("pause");
return 0;
}

This line
int *Angka = new int(x);
creates an integer on the heap with a value held by x which here it is 0.
You are accessing memory which you should not, and as mentioned by #fredrik it may cause a buffer overflow.
If you want to create an array on the heap you should do
int *Angka = new int[x];
This creates an array (on heap) of size x.
But since you are using c++ it's better to use vectors, you can simply create a vector with
std::vector<int> Angka;
Vector will take care of memory allocation and all other stuff that you would have to handle if you were to create an array with new.

Related

GMP mpz_t variable being set with incorrect value

I've been working on the Euler 29 problem for a few days and am having difficulty getting the mpz_t type to work correctly. The objective is to iterate through a^b for values of 2 <= a,b <= 100 and count the nonrepeat values.
Using vector I was able to store the values using pointers in an array like so:
mpz_t a;
mpz_init(a);
vector<mpz_t*> numbers;
numbers.push_back(&a);
However, when running the full program below you can see that after it inserts the first value 4, it doesn't insert any new values. This is because the temp value being compared to rop is not being set to what is already in the array, and instead is set to the value shared by rop.
#include <iostream>
#include <vector>
#include <chrono>
#include "gmp.h"
using namespace std;
int main()
{
auto start = std::chrono::high_resolution_clock::now();
int solution = 0;
bool found = false;
int r = 10;
mpz_t rop;
mpz_init(rop);
mpz_t temp;
mpz_init(temp);
vector<mpz_t*> numbers;
for(int a = 2; a <= 5; a++)
{
for(int b = 2; b <= 5; b++)
{
mpz_ui_pow_ui(rop, a, b);
for(int i = 0; i < numbers.size(); i++)
{
cout << "i: " << i << endl;
cout << "rop: ";
mpz_out_str(stdout,10,rop);
cout << endl;
mpz_set(temp,*(numbers.at(i)));
cout << " temp: ";
mpz_out_str(stdout,10,temp);
cout << endl;
r = mpz_cmp(rop,temp);
cout << " r: " << r << endl << endl;
if(r == 0)
{
found = true;
break;
}
}
if(found == false)
{
numbers.push_back(&rop);
solution++;
cout << "pushed! " << endl << endl;
}
found = false;
}
}
auto done = std::chrono::high_resolution_clock::now();
cout << "Solution: " << solution << endl << endl;
cout << "Program completed in " << std::chrono::duration_cast<std::chrono::milliseconds>(done - start).count() << " milliseconds." << endl;
}
This line of code should be setting temp equal to 4 at the start of the forloop, but instead sets it equal to rop:
mpz_set(temp,*(numbers.at(i)));
Since the problem clearly has to do with the fact I'm using pointers and passing the actual address in memory to store these mpz_t variables, how can I change the code so that it is able to work properly? I'm under the impression using the function mpz_clear(rop) after each push_back to the numbers vector wouldn't work as it releases the address from memory.
I figured out that due to the way mpz_t variables work the mpz_set function does not work with a pointer to mpz_t type variables as a parameter.
Instead, I was able to get the program to work by assigning the mpz_get_str function to a string and pushing that to a vector of strings to check for repeat values.
mpz_t rop;
mpz_init(rop);
char * num;
vector<string> numbers;
num = mpz_get_str(num,10,rop)
numbers.push_back(num);

Integers not getting added up correctly but doubles are working fine

I know this isnt the right kind of question to be asking, but for the life of me I could not figure out what is causing this problem.
I need to write a problem that takes a set number of integers or doubles and returns their sum.
I have written the code to make this work, making sure to check each time I changed something.
#include<iostream>
using namespace std;
template <class T>
class totalClass
{
private:
T *p;
T Total;
T sum;
int size;
public:
T total(int x)
{
size = x;
p = new T[x];
for (int i = 0; i < size; i++)
p[i] = T();
if (size > 1)
{
for (int i = 0; i < size; ++i)
{
cin >> sum;
Total += sum;
}
}
return Total;
}
};
int main()
{
int size, result1;
double result2;
cout << "Enter: ";
cin >> size;
cout << "the number of ints you wish to enter: Enter: " << size << " integers:";
totalClass<int> test;
result1 = test.total(size);
cout << " Total = " << result1 << endl;
cout << "Enter: ";
cin >> size;
cout << "the number of doubles you wish to enter: Enter: " << size << " doubles:";
totalClass<double> test2;
result2 = test2.total(size);
cout << " Total = " << result2 << endl;
}
My doubles are getting added up correctly but my integer addition always seems to add up to some crazy number. Is there something wrong with my problem that I cannot see?
If you forget to initialize a variable and attempt to use it or do math with it, you might end up with "crazy numbers." Make sure all of your variables are Initialized.

Getting error in an array comparing program in a specific input

I have written a small program which compares two arrays with custom array size. Whenever I set the array size to 4, the program does not work correctly on comparing the fourth member of each array.
(when I set x to 4, the fourth array members does not get compared correctly)
This is the code:
#include <iostream>
using namespace std;
int main()
{
int x;
std::cin >> x;
int i =1;
int arr[x];
int arr2[x];
while(i <= x)
{
std::cout << "Enter row " << i << " of arr\n";
std::cin >> arr[i];
i++;
}
i = 1;
while(i <= x)
{
std::cout << "Enter row " << i << " of arr2\n";
std::cin >> arr2[i];
i++;
}
for(int a = 0;a <= x;a++)
{
if(arr[a] == arr2[a])
std::cout << "row " << a << " is true\n";
}
}
You have an out of bound access, which yields undefined behavior. Recall that indices into raw arrays start with zero, not with one. Hence,
int i = 0;
is the correct initialization of the index, while the first loop must be changed to
while (i < x) { /* ... */ }
Then, the assignment of i needs again to be adjusted to
i = 0;
and the two remaining loops to
while (i < x) { /* ... */ }
for (int a = 0; a < x; a++) { /* ... */ }
As a side note, you are using variable length arrays (arr and arr2), which is non-standard C++ (see this thread for more info). Prefer std::vector for a simple container with runtime-dependant size.
i = 1;
while(i <= x)
{
std::cout << "Enter row " << i << " of arr2\n";
std::cin >> arr2[i];
i++;
}
you are storing element in array starts with 1 index
for(int a = 0;a <= x;a++)
{
if(arr[a] == arr2[a])
std::cout << "row " << a << " is true\n";
}
But comparing by starting from 0 index.
keep consistency either start from 0 or 1
for(int a = 1;a <= x;a++)
{
if(arr[a] == arr2[a])
std::cout << "row " << a << " is true\n";
}
it will work..

How do you correctly pass arrays with pointers to a function?

I have to dynamically allocate an array and pass it to a function to calculate odds of a weighted die being rolled. Whenever I run through my code the function doesn't remember the values added to my array and returns random values, what's wrong about the way I'm passing *weight into the roll function? I added print statements after adding weights in and the weight is entered fine up until it's passed to the function via pointer.
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int roll (int sides, double *weight) {
int total[sides + 1];
total[0] = 0;
for (int i = 1; i <= sides; i++) {
total[i] = total[i - 1] + weight[i];
}
int current = (rand() % total[sides + 1] - 1 + 1);
//cout << current << " ";
for (int i = 1; i <= sides; i++) { // 1 to weight 1,,,,, weight 1 to weight
2
if (current <= total [i] && current > total[i - 1]) {
current = i;
}
}
return current;
}
Function that is supposed to retrieve the random number rolled. ^
int main () {
int sides = 0;
int rolls = 0;
int answer = 0;
int currentRoll = 0;
bool done = false;
double* weight;
double totalWeight;
srand(time(NULL));
cout << "Dice Roll Menu: " << endl << "1. Specify an output file" << endl <<
"2. Enter sides and weight for a die" << endl << "3. Simulate a specified
number of rolls of the weighted die" << endl << "4. Exit" << endl;
while (done != true) {
cout << endl << "Enter a number that corresponds to you choice: ";
cin >> answer;
while (answer == 2) { //SIDES
cout << "Please enter the number of sides on the die (must be
greater than two): ";
cin >> sides;
if (sides < 2) {
cout << "Invalid input, try again." << endl;
}
else {
weight = new double[sides + 1];
for (int i = 0; i < sides + 1; i++) {
weight[i] = 0;
}
break;
}
}
while (answer == 2) {
totalWeight = 0;
for (int i = 1; i <= sides; i++) { //WEIGHT
cout << "Enter a weight for side " << i << ": ";
cin >> weight[i];
cout << "TEST: " << weight[i] << endl;
totalWeight = weight[i] + totalWeight;
if (weight[i] < 0) {
cout << "Invalid input. Try again.";
totalWeight -= weight[i];
i--;
}
}
break;
}
Loop that determines sides and weight and dynamically allocates the array. ^
while (answer == 3) {
cout << "Enter the amount of rolls you would like to perform: ";
cin >> rolls;
if (rolls < 0) {
cout << "Invalid input. Try again.";
}
else {
else if (totalWeight == 0) {
cout << "Please enter weights of the dice first!" << endl;
answer = 1;
}
else {
done = true;
break;
}
}
}
//ACTUAL CODE HERE
for (int i = 1; i <= rolls; i++) { //CALCULATES
currentRoll = roll(sides, &weight[i]);
cout << currentRoll << " ";
}
}
Perhaps many of the misunderstandings that dominate the comments have to do with simply using C++ (and yet without using std::containers).
My out-of-the-box idea (or just plain crazy) is that there really is no conflict between:
"I have to be able to complete this program using 'dynamically allocated arrays', sadly I am not allowed to use vectors
yet all concerned seemed to agree that this is a C++ class assignment.
So, we need think of a way to create an array dynamically (I consider this part easy, not sure why). We want something with compile time fixed size. The array must exist in dynamic memory. (And no std containers.)
The goal has also been stated more simply
I have to dynamically allocate an array and pass it to a function to
calculate odds of a ...
I propose the following. (This code compiles and runs. )
#include <iostream>
using std::cout, std::flush, std::endl;
// Step 1 - wrap an array inside a class
class Array_t
{
const int m_sz;
int64_t* m_arr;
public:
Array_t()
: m_sz(128)
, m_arr (new int64_t[m_sz]) // allocate array in dynamic memory
{
// init for easy sum ... -------------v
for (int j=0; j<m_sz; j+=1) m_arr[j] = 1; // easy sum
}
~Array_t() = default;
int64_t sum() {
int64_t retVal = 0;
for (int i=0; i<m_sz; i+=1)
retVal += m_arr[i]; // direct access to the data!
return retVal;
}
};
// If your C++ 'Hello World' has no class ... why bother?
// Step 2 - auto var the above
class DUMY999_t
{
public:
DUMY999_t() = default;
~DUMY999_t() = default;
int operator()(int argc, char* argv[]) { return exec(argc, argv); }
private:
int exec(int , char** )
{
// here is the array wrapped in a class, an automatic var!
// the array is dynamically allocated in the class (see ctor)
Array_t arr;
// ctor provides the compile time constant
// Step 3
// pass the array (in the class) to some function foo()
cout << "\n foo(arr) :" << foo(arr) << endl;
// Step 4 - can we solve the 'how pass' question?
// It should be obvious that foo is redundant ...
// the following is both more direct
// and object-oriented (a good thing)
// >>> put the function in the object that has the data <<<
cout << "\n arr.sum() :" << arr.sum() << endl;
// invoke an object method which has
// direct access to the data!
return 0;
}
// why pass the data to the function? (c-style?)
int64_t foo(Array_t& arr)
{
return arr.sum();
}
// why not install the function into the object? (c++?)
}; // class DUMY999_t
int main(int argc, char* argv[]) { return DUMY999_t()(argc, argv); }
Typical output:
foo(arr) :128
arr.sum() :128

Using pointer arithmetic to add the contents of two arrays and save to an empty array

So I have written a function that should simply add the values of each element stored in two separate arrays, and save them to a third array.
I don't understand what the issue is, I am simply adding together the value of the int stored at the location referenced by each of my pointers, and saving it to my third, empty, array.
My code compiles just fine, but when I loop to print the contents of my third array (which should contain the sum of the two previous arrays elements at their respective indexes) it just prints a bunch of memory addresses. What gives?
EDIT: I fixed my while loop to perform the arithmetic, and everything is working well. My working code is below. Hope it helps someone else.
#include<iostream>
#include<stdlib.h>
using namespace std;
void arrayAdd(int firstArray[], int secondArray[], int targetArray[], int size){
int *firstPtr = firstArray;
int *secondPtr = secondArray;
int *tragetPtr = targetArray;
while (firstPtr <= &firstArray[size - 1] ){
//add the first two array elements
*tragetPtr = (*firstPtr + *secondPtr);
// point to the next location
*firstPtr++;
*secondPtr++;
*tragetPtr++;
}
}
int main() {
int totalElements;
const size_t ARRAY_SIZE = 50;
int firstIntegerArray[ARRAY_SIZE];
int secondIntegerArray[ARRAY_SIZE];
int thirdIntegerArray[ARRAY_SIZE];
cout << "Please enter the total number of elements for your array: ";
cin >> totalElements;
for(int i = 0; i < totalElements; i++){
cout << "Please enter a value for the first array at index " << i << ": ";
cin >> firstIntegerArray[i];
}
for(int i = 0; i < totalElements; i++){
cout << "Please enter a value for the second array at index " << i << ": ";
cin >> secondIntegerArray[i];
}
//run our arrayAdd function
arrayAdd(firstIntegerArray, secondIntegerArray, thirdIntegerArray, totalElements);
cout << "The conents of your two arrays added together is; " << endl;
for(int i = 0; i < totalElements; i++){
cout << thirdIntegerArray[i] << ", ";
}
return 0;
}
A local array decays to a pointer when it is passed to a function, so you can't use sizeof on it anymore. Indeed this:
void arrayAdd(int firstArray[]) {
int *firstPtr = firstArray;
std::cout << "sizeof(firstArray) == " << sizeof(firstArray) << std::endl;
std::cout << "sizeof(firstPtr) == " << sizeof(firstPtr) << std::endl;
}
int main() {
int test[] = {1,2,3,4,5,6,7,8,9,0};
arrayAdd(test);
return 0;
}
Prints:
sizeof(firstArray) == 8
sizeof(firstPtr) == 8
on my 64 bit machine.
Casting int[] to int* doesn't change anything since it already became a pointer as an argument. You should pass the size of the array to the method or, since you are working with C++, use an std::array or std::vector which will just solve any problem.