How the assigned value to variable gets changed automatically? - c++

When I am providing input for std::cin >> diff; it takes the input value, and the moment I am entering the value of array, the diff variables value gets changed and sets the value of 4th element of the array.
Please help me where is it going wrong. I have tried with fflush(std). But it did not help me.
I am using Visual Studio 2010 Ultimate edition.
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int i, num;//[]={0};
int diff = 0;
int numset[] = {0};
int temp, cnt;
cnt = num = i = 0;
std::cout << "Enter your number and difference : ";
//fflush(stdin);
std::cin >> num ;
std::cin >> diff;
cout << "Enter array Elements : \n";
for(i = 0; i < num; i++)
{
cin >> numset[i];
//fflush(stdin);
}
for(i = 0; i < num; i++)
{
for(int j = i; j < num; j++)
{
if(i == j)
{
temp = numset[j];
}
else
{
if((diff == (numset[j] - temp)) || (((-1)*diff) == (numset[j] - temp)))
{
cnt++;
}
}
}
}
cout << cnt << endl;
system("pause");
return 0;
}

You're accessing beyond the bounds of the array numset, so your code has Undefined Behaviour (UB) and anything could happen. It could overwrite variables on stack (as it does in your case), it could crash, it could order pizza online.
numset is declared as a single-element array, so accessing numset[i] for i > 0 results in UB. You should probably change numset to be a std::vector<int> and use push_back() to append numbers to it.

Related

how to create an array of Bitset in c++

I want to create an array of Bitset .Binary Bitset(example "100","1010",etc)
After that I want to input from user and store in the the Bitset .
I have tried the following line but it says error.
#include<bits/stdc++>
using namespace std;
int main()
{
int n,i;
string bit_string;
cin>>n // size of Bitset array.
bitset<8> brr[n];//
for(i=0;i<n;i++)
{
cin>>bit_string;
brr[i](bit_string);
}
return 0;
}
I want to create n Bitset each of size 8 bits.Where n is given by user.
my input is binary string like.
"110010","001110"
please help
The error ocurrs because you are trying to creat a C-style array using n which is not compile-time constant. It's not possible to creat a C-style array without being n known at compile time.
The following is a good way to do what you want
Creat a std::vector<std::bitset<8>> to hold your bitset<8>s, as follows.
Note that the code ignores the excess of characters in strings iput like "111111110" (makes it "11111111") and treats any character except '1' as if it were '0' and if the input string is less than 8 characters, the code adds zeros by the default of the bitsets
#include <vector>
#include <bitset>
#include <iostream>
int main() {
int n, i;
std::string bit_string;
std::cout << "Enter the size";
std::cin >> n; // size of Bitset array.
std::vector<std::bitset<8>> brr(n);//
for (i = 0; i < n; i++) {
std::cin >> bit_string;
for (int j{}; j < bit_string.size() && j < 8; ++j) {
brr[i][j] = (bit_string[j] == '1') ? 1 : 0;
}
}
//To test
for(auto const& el :brr)
{
for(int i{}; i < 8;)
std::cout << el[i++];
std::cout<<"\n";
}
}
See Why is "using namespace std;" considered bad practice?
and
Why should I not #include <bits/stdc++.h>?
For dynamic count of the objects , Please try vector<> instead of array[]
#include<bits/stdc++>
using namespace std;
int main()
{
int n, i;
string bit_string;
cin >> n; // size of Bitset array.
vector<bitset<8>> arr; //size()=>0
arr.resize(n); //size()=>n
for (i = 0; i < n; i++)
{
cin >> bit_string;
bitset<8>& br = arr[i]; //get the i of n
int maxlen = 8;
if (bit_string.size() <= 8)
maxlen = bit_string.size();
else
cout << "warning invalid len " << bit_string.size() << " of " << bit_string << endl;
for (int j = 0; j < maxlen; j++)
{
if (bit_string[j] == '1')
br.set(j, true);
}
//cout << endl << br << endl; //output test
}
return 0;
}
If you still want to use array , please try this way
#include<bits/stdc++>
using namespace std;
int main()
{
int n, i;
string bit_string;
cin >> n; // size of Bitset array.
bitset<8>* arr = new bitset<8>[n];
for (i = 0; i < n; i++)
{
cin >> bit_string;
bitset<8>& br = arr[i]; //get the i of n
int maxlen = 8;
if (bit_string.size() <= 8)
maxlen = bit_string.size();
else
cout << "warning invalid len " << bit_string.size() << " of " << bit_string << endl;
for (int j = 0; j < maxlen; j++)
{
if (bit_string[j] == '1')
br.set(j, true);
}
//cout << endl << br << endl; //output test
}
delete[] arr; //IMPROTAND , delete the array and free memory
return 0;
}

Can someone help to find the reason for s runtime error in this code?

The code runs fine in my compiler but shows runtime error on codeforces. I found out that I should avoid unitialized variables but I think I've already covered that.
#include <iostream>
using namespace std;
int main()
{
int i, n, flag = 1, k = 1;
int hours[n];
int minutes[n];
cin >> n;
for (i = 0; i < n; i++)
{
cin >> hours[i];
cin >> minutes[i];
}
for (i = 0; i < n; i++)
{
if (hours[i] == hours[i + 1] && minutes[i] == minutes[i + 1])
{
flag++;
if (flag > k)
k = flag;
}
else
flag = 1;
}
cout << k;
return 0;
}
The problem lies here
int i, n, flag = 1, k = 1;
int hours[n];
int minutes[n];
You declare variables n, but you don't initialize it, and then you use it to specify an array size. Uninitialized variables of type int contain garbage data, and using it is undefined behavior, whatever happens is unspecified, and you can not rely on it.
If you must create an array of size specified by a user input, you need to allocate at runtime.
int *hours;
int *minutes;
cin >> n;
hours = new int[n];
minutes = new int[n];
// Rest of the code
// Remember to delete them
delete[] minutes;
delete[] hours;
Better yet, use a container provided by the standard library, a std::vector would be a perfect container to use here
#include <vector>
std::vector<int> hours;
std::vector<int> minutes;
cin >> n
hours.resize(n);
minutes.resize(n);
VLAs are not standard C++ but are allowed as an extension. The first problem in your code is that you use the variable n without initialization. This causes undefined behavior according to the standard.
You need to move the call to cin() to above the arrays that use n at declaration. The second problem in your code is that the expression inside the if statement attempts to access an element outside the bounds of your array. This also causes undefined behavior.
Here is a refined version of your code:
#include <iostream>
using namespace std;
int main()
{
int n;
int k = 1;
int flag = 1;
cout << "Enter a value for n:" << endl;
cin >> n;
int *hours = new int[n];
int *minutes = new int[n];
cout << "Enter values for hours:" << endl;
for (int i = 0; i < n; i++)
{
cout << i + 1 << ":";
cin >> hours[i];
}
cout << "Enter values for minutes:" << endl;
for (int i = 0; i < n; i++)
{
cout << i + 1 << ":";
cin >> minutes[i];
}
// note here: 'i' goes to (n - 1) instead of (n) so as not to be out of range
for (int i = 0; i < n - 1; i++)
{
if ((hours[i] == hours[i + 1]) && (minutes[i] == minutes[i + 1]))
{
flag++;
if (flag > k)
{
k = flag;
}
}
else
{
flag = 1;
}
}
cout << "The value of k is: " << k << endl;
delete hours;
delete minutes;
return 0;
}

about the function strcpy_s

I want to output the smallest letters of the first letter of three countries, this is the code:
#include<iostream>
#include<string>
using namespace std;
int main()
{
void smallest_string(char str[][30], int);
int i;
char country_name[3][30];
for (i = 0; i < 3; i++)
cin >> country_name[i];
smallest_string(country_name, 3);
system("pause");
}
void smallest_string(char str[][30], int n)
{
int i;
char string[30];
***strcpy_s(string, str[0]);***
for (i = 0; i < n; i++)
if (strcmp(str[i], string) < 0)
strcpy_s(string, str[i]);
cout << endl << "the smallest string is:" << string << endl;
}
In this code strcpy_s(string, str[0]);, it seems can be deleted. Why?
The line strcpy_s(string, str[0]); is essential if you want your loop to start from i = 1.
However, since you start it from i = 0 it is not strictly required if you also define the following start condition: string[0] == CHAR_MAX and string[1] == 0. But if that is not the case then you will experience undefined behavior.

display wheter or not an array entered by the user is unique or not

I am new to C++ I am making an array based off of user input and displaying whether the array is unique or not. my initial thought is I have to end up creating another array to store values and then compare the elements. My code compiles without errors but does not do what I want it to do. I can't used advanced methods such as hashmaps or vectors. Any help or insight is greatly appreciated!
#include <iostream>
#include <string>
using namespace std;
int main()
{
int myArray[6];
string name;
int i, k;
int ov = 0;
int newVal = 0;
for (int index = 0; index < 6; index++)
{
cout << "Enter number a number: ";
cin >> myArray[index];
}//end loop for
for (i = 0; i < 6; i++)
{
ov = myArray[i];
}
for (k = i + 1; k < 6; k++)
{
if (ov == myArray[k])
{
newVal = 1;
}
}
if (newVal == 1)
{
cout << "Not all unique";
}
else
{
cout << "All unique";
}
cin.get();
return 0;
}

Heap corruption detected due to array usage

Sorry, I'm a brand new newbie to C++ and programming and I'm getting a heap corruption error. I think Im writing in unallocated memory but I can't seem to find where the error is... the program is soppuse to take user input values and rearrange them so that they would ascend. I'm also learning templates too.
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
template <typename T>
void sort(T arrayz[], int size, char ch)
{
T temporary;
int k, j;
if (ch = 'a')
{
for (k = 0; k < size; k++)
{
for (j = 0; j < size; j++)
{
temporary = arrayz[j];
arrayz[j] = arrayz[j + 1];
arrayz[j + 1] = temporary;
}
}
}
}
int main()
{
int choices, range, i;
int x;
char ch;
cout << ("Enter the amount of numbers you want =>");
cin >> x;
int *numbers = new int[x];
if (!numbers)
{
cout << "Memory Allocation error!";
cin.get();
exit(1);
}
for (int i = 0; i<x; i++)
{
cout << "Option number" << i + 1 << " =>";
cin >> numbers[i];
}
cout << "Do you want ascending or descending values (a/d) =>" ;
cin >> ch;
if (ch = 'a')
{
sort(numbers, x, ch);
}
else if (ch = 'd')
{
sort(numbers, x, ch);
}
delete[] numbers;
fflush(stdin);
cin.get();
return 0;
}
In your sort function, you are accessing elements at index j + 1. However, this is out of bounds. The valid indexes for your arrayz array are 0 through size-1. When j is size-1, j+1 is size, which accesses past the end of the array.