Unexpected value while placeing integers into an array - c++

I am trying to fill an array with different integers, but it doesn't work as expected.
#include <iostream>
using namespace std;
int main(){
int i=0;
int num;
int MyArray[]={};
while (true) {
cout<<"sayi giriniz"<<endl;
cin>>num;
MyArray[i]=num;
i++;
for (int j=0; j<i; j++) {
cout<<MyArray[j]<<endl;
}
}
return 0;
}
https://imgur.com/a/tANGpSY
When I enter the 3rd value it gives an unexpected result.

int MyArray[]={};
Now, MyArray has a size of 0, so any indexes that you tried to access MyArray will cause undefined behavior.
If you want to make an array that is dynamically in size, use std::vector in the <vector> header.
Change
int MyArray[]={};
to
std::vector<int> MyArray;
This:
MyArray[i]=num;
i++;
To this:
MyArray.push_back(num); // you don't even need i
This
for (int j=0; j<i; j++) {
cout<<MyArray[j]<<endl;
}
To this:
for(const auto &i : MyArray) // range based for loop, recommend
{
std::cout << i << '\n';
}
Also, using namespace std; is bad, so don't use it.

If you want to take input and are unsure about the number of elements, you should use a vector. The array which you have made is of 0 size. It will surely give you an error.

Related

I want to store input in array. and print the array elements but cout line isn't working

I am new in programming,
basically in this program, it takes input from user and storing in array, 5 elements. After loop ends it should give the elements back but it seems that the last line is not working.
include<iostream>
using namespace std;
int main(){
int size=5;
string guess[size];
for (int i=0; i<size;i++){
cin>>guess[size];
}
cout<<guess[size];
return 0;
}
guess[size] is out of bounds. The last valid index in an array with size elements is size-1. Further, string guess[size]; is not valid C++ when size is not a constant expression. At the very least it should be const int size = 5;. You wrote a loop to take input and you also need a loop to print all elements.
This is the correct loop to read the input:
const int size=5;
std::string guess[size];
for (int i=0; i < size; i++){
std::cin >> guess[i];
}
You can modify it so that both input and output should use i as the loop subscript.
//cover #
#include<iostream>
using namespace std;
int main(){
int size=5;
string guess[size];
for (int i=0; i<size;i++){
cin>>guess[i];
}
for (int i = 0; i < size; ++i) {
cout<<guess[i];
}
return 0;
}
Use Range based Loops when You want to Print whole array, so you won't get an "Out-Of-Bounds" error. Because the Index in array are Zero Based Always remember the last index is (length_of_array - 1)
using namespace std;
int main()
{
int size = 5;
string guess[size];
for (int i=0; i<size;i++)
{
cin >> guess[i];
}
// range based loop
for (int i : guess)
{
cout << i << endl;
}
return 0;
}

How can I eliminate garbage value in this output?

In this below program, I'm trying to marge 2 arrays into a single vector, but while returning the function I'm getting additional garbage values along with it.
Please anyone suggest me how to remove those!
#include <bits/stdc++.h>
#include <vector>
#include <string>
using namespace std;
vector <int> merge(int a[],int b[]){
vector <int> marr1;
marr1.clear();
int i=0,j=0;
while(i+j <= ((*(&a+1)-a)+(*(&b+1)-b)))
{
if ((i<= *(&a+1)-a)){
marr1.push_back(a[i]);
i++;
}
else{
marr1.push_back(b[j]);
j++;
}
}
sort(marr1.begin(),marr1.end());
return marr1;
}
int main(){
//array imlementation
int arr1[] = {5,7,4,5},arr2[] = {8,3,7,1,9};
vector <int> ans;
ans.clear();
ans = merge(arr1,arr2);
for (auto i=ans.begin();i<ans.end();++i){
cout<<*i<<"\t";
}
}
output produced:
0 0 0 0 1 3 4 5 5 7 7 8 9 32614 32766 4207952 1400400592
You want something like this:
include <iostream>
#include <vector>
#include <algorithm> // <<<< dont use #include <bits/stdc++.h>,
// but include the standard headers
using namespace std;
vector <int> mergeandsort(int a[], int lengtha, int b[], int lengthb) { // <<<< pass the lengths of the arrays
vector <int> marr1; // <<<< and use meaningful names
// marr1.clear(); <<<< not needed
for (int i = 0; i < lengtha; i++)
{
marr1.push_back(a[i]);
}
for (int i = 0; i < lengthb; i++)
{
marr1.push_back(b[i]);
}
sort(marr1.begin(), marr1.end());
return marr1;
}
int main() {
int arr1[] = { 5,7,4,5 }, arr2[] = { 8,3,7,1,9 };
vector <int> ans;
// ans.clear(); <<<< not needed
ans = mergeandsort(arr1, 4, arr2, 5);
for (auto i = ans.begin(); i < ans.end(); ++i) {
cout << *i << "\t";
}
}
Look at the <<<< comments for explanations.
There is still room for improvement:
passing the hard coded lengths of the arrays in mergeandsort(arr1, 4, arr2, 5) is bad practice, if you add/remove element from the arrays, you need to change the lengths too.
you shouldn't use raw arrays in the first place but vectors like in vector<int> arr1[] = { 5,7,4,5 };, then you don't need to care about the sizes as a vectors knows it's own size. I leave this as an exercise for you.
Since you're not passing the length of the array, there is no way inside the merge function to know about their length. Your program seems to produce undefined behavior as can be seen here. If you execute this program again and again you'll notice that the output changes which is an indication of undefined behavior.
Secondly, you're using std::vector::clear when there is no need to use it in your program. I have commented it in the code example i have given below.
You can use pass the length of the arrays as arguments to the merge function. Below is the complete working example:
#include <bits/stdc++.h>
#include <vector>
#include <string>
using namespace std;
vector<int> merge(int a[], int lengthA, int b[], int lengthB){
vector <int> marr1;
//marr1.clear();//no need for this since the vector is empty at this point
for(int i = 0; i< lengthA; ++i)
{
//std::cout<<"adding: "<<a[i]<<std::endl;
marr1.push_back(a[i]);
}
for(int i = 0; i< lengthB; ++i)
{
//std::cout<<"adding: "<<b[i]<<std::endl;
marr1.push_back(b[i]);
}
sort(marr1.begin(),marr1.end());
return marr1;
}
int main(){
//array imlementation
int arr1[] = {5,7,4,5},arr2[] = {8,3,7,1,9};
vector <int> ans;
//ans.clear();//no need for this since the vector is empty at this point
ans = merge(arr1,4, arr2, 5);
for (auto i=ans.begin();i<ans.end();++i){
cout<<*i<<"\t";
}
}
You pass two int[] which degrade to pointers. This means you cannot tell the number of elements which you attempt to do with i+j <= ((*(&a+1)-a)+(*(&b+1)-b)). Either pass in a length of each array, or even better (C++) pass in two vectors instead. Also, if you don't know the STL has a merge() function in <algorithm>.

Weird Array Stuff (Array indexes getting values without me setting it)

I am trying to write a sudoku solver.
I got the input almost done, but something strange started happening. On the index [i][9] of int sudoku[i][9], there are numbers present that I have never put there.
For example, when I run the code below with the input that is commented below using namespace std;, the output is:
410270805
085146097
070580040
927451386
538697412
164328759
852704900
090802574
740965028
Of course, I only need 0 through 8, but I was wondering what is causing integers to appear at the 9th index.
This is the code:
#include <iostream>
#include <math.h>
#include <cstdlib>
using namespace std;
/*
410270805
085146097
070580040
927451386
538697412
164328759
852704900
090802574
740965028
*/
int main()
{
int sudoku[9][9];
int solving[9][9][9];
int input;
for (int i=0; i<=8; i++) {
cin >> input;
int j;
int k;
for (j=8, k=1; j>=0; j--, k++) {
int asdf = input/pow(10,k-1);
sudoku[i][j] = asdf % 10;
}
}
cout << endl;
for (int i=0; i<=8; i++) {
for (int j=0; j<=9; j++) {
cout << sudoku[i][j];
}
cout << endl;
}
return 0;
}
Accessing elements outside of the defined region of an array is Undefined Behavior (UB).
That means it could:
Allow you to access uninitialized space (what yours is doing hence the random numbers)
Segfault
Any number of other random things.
Basically don't do it.
In fact stop yourself from being able to do it. Replace those arrays with std::vectors and use the .at() call.
for example:
std::vector<std::vector<int>> sudoku(9, std::vector<int>(9, 0));
for (int i=0; i<=8; i++) {
for (int j=0; j<=9; j++) {
cout << sudoku.at(i).at(j);
}
cout << endl;
}
Then you will get a thrown runtime exception that explains your problem instead of random integers or segfaults.
I think I found your problem, at your very last for loop you used j <= 9 instead of j <= 8. You then tried to write (j) leaving the possibility of it writing 9 wide open. Try replacing that 9 with 8.

Code failure insert digits before data of the vector

I am supossed to do a code using function which after asking the user for input,puts number before the vector like this:
if vector is 11,12,13,14
new vector is 1 11 2 12 3 13 4 14 until the vector finishes and then I have to print it but I get an error of vector subscript out of range,aprecciate any help.
Here is my code
#include<iostream>
#include<string>
#include<vector>
using namespace std;
vector<double> llena_vector(int x,vector<double> ingreso)
{
cout<<"Ingrese numeros: ";
while(cin>>x);
ingreso.push_back(x);
return ingreso;
}
vector<double> arma_vector(int contador,vector<double> intercalado)
{
int i=0;
for(contador=1;contador< intercalado.size()+1;contador++);{
intercalado.insert(intercalado.begin()+i,contador);i++;}
return intercalado;
}
vector<double> imprime_vector(int cuenta,vector<double> imprimir)
{
for(cuenta=0;cuenta<imprimir.size();cuenta++);
cout<<imprimir[cuenta]<<" ";
return imprimir;
}
int main()
{
int y=0;
int q=0;
int w=0;
int f=0;
vector<double> usuario;
vector<double> guardar;
vector<double> resultado;
vector<double> print;
guardar= llena_vector(y,usuario);
resultado=arma_vector(q,guardar);
print=imprime_vector(w,resultado);
system("pause");
}
Here is a cleaner version of the code, in working condition.
#include <iostream>
#include <vector>
using namespace std;
void fill_vector(vector<double>& v)
{
cout << "Enter 5 numbers." << endl;
for (int i = 0; i < 5; ++i)
{
double d;
cin >> d;
v.push_back(d);
}
}
void insert_count(vector<double>& v)
{
size_t size = v.size();
for (size_t i = 0, j = 0; i < size; ++i, j += 2)
{
vector<double>::iterator pos = v.begin() + j;
v.insert(pos, i + 1);
}
}
void print_vector(vector<double>& v)
{
for (size_t i = 0; i < v.size(); ++i)
cout << v[i] << " ";
cout << endl;
}
int main()
{
vector<double> v;
fill_vector(v);
insert_count(v);
print_vector(v);
}
Like others (may have) pointed out:
you didn't need to pass by value (you're basically passing around a bunch of copies), you can pass by reference instead to reduce overhead and speed it up
you shouldn't put semicolons (;) directly behind your loop statements
size_t is often better than int when looping on size
you included <string> when it wasn't being used
you were passing arguments that weren't needed (e.g. a counter)
you used a while loop for user input, but it's only appropriate when piping in data otherwise it will loop forever; a for loop with a known count is more appropriate for user input
the function that inserted numbers between the existing elements had an error, you were incorrectly calculating the position to insert
your code formatting was a mess, making the code very difficult to read
you shouldn't pollute the namespace (i.e. using namespace std), but I left it as is since it's common in example code
if you're using C++11, I recommend using a for-each loop for printing the vector, and the auto keyword when declaring the iterator
i guess there is a typo: you should remove the last ; in for(cuenta=0;cuenta<imprimir.size();cuenta++);
Edit: as pointed by jrd1, you have this typo in all your for and while loops...
To begin with, your code has a number of issues. But, I've modified it to keep it as similar to your original.
#include <iostream>
#include <string>
#include <deque>
#include <cstdlib>
using namespace std;
deque<double> llena_deque(int x, deque<double> ingreso)
{
cout<<"Ingrese numeros: ";
while(cin>>x)
ingreso.push_back(x);
return ingreso;
}
deque<double> arma_deque(int contador, deque<double> intercalado)
{
int size = intercalado.size()+1;
for(int i=1; i < size; ++i) {
cout << i << endl;
intercalado.push_front(i);
}
return intercalado;
}
deque<double> imprime_deque(int cuenta, deque<double> imprimir)
{
for(cuenta=0;cuenta<imprimir.size();cuenta++)
cout << imprimir[cuenta] << " ";
return imprimir;
}
int main()
{
int y=0;
int q=0;
int w=0;
int f=0;
deque<double> usuario;
deque<double> guardar;
deque<double> resultado;
deque<double> print;
guardar= llena_deque(y,usuario);
resultado=arma_deque(q,guardar);
print=imprime_deque(w,resultado);
return 0;
}
All your loops had ; at the end of them. That's one reason why you're getting your errors, as the semi-colon terminates a statement - hence, your loops were never truly accessing the vectors, which is why you were getting the memory access violations.
You're passing all your memory by value (which could potentially be slow). Consider using references.
Your operations suggest that you constantly need to keep pushing new data in front of your vector. If so, then use deque (as I did) as it is has functionality designed explicitly for that purpose (insert operations at both ends).
Although, I will say that the logic of your code is quite puzzling at times: i.e. in arma_vector, why pass the value of contador if you don't even use it? You could have used i instead...

implementation counting sort

here is code for counting sorting
#include <iostream>
using namespace std;
int main(){
int a[]={2,3,1,2,3};
int n=sizeof(int)/sizeof(int);
int max=a[0];
for (int i=1;i<n;i++) {
if (a[i]>max) {
max=a[i];
}
}
int *output=new int[n];
for (int i=0;i<n;i++) {
output[i]=0;
}
int *temp=new int[max+1];
for (int i=0;i<max+1;i++) {
temp[i]=0;
}
for (int i=0;i<n;i++){
temp[a[i]]=temp[a[i]]+1;
}
for (int i=1;i<max+1;i++) {
temp[i]=temp[i]+temp[i-1];
}
for (int i=n-1;i>=0;i--) {
output[temp[a[i]]-1]=a[i];
temp[a[i]]=temp[a[i]]-1;
}
for (int i=0;i<n;i++) {
cout<<output[i]<<" ";
}
return 0;
}
but output is just 2,only one number. what is wrong i can't understand please guys help me
int n=sizeof(int)/sizeof(int);
is wrong. That just assigns 1 to n.
You mean
int n=sizeof(a)/sizeof(int);
I've not looked beyond this. No doubt there are more problems, but this is the most significant.
This is the kind of thing you can work out very easily with a debugger.
Look at this expression:
int n=sizeof(int)/sizeof(int);
What do you think the value of n is after this? (1)
Is that the appropriate value? (no, the value should be 5)
Does that explain the output you are seeing? (yes, that explains why only one number is shown)
My advice would be that if you're going to do this in C++, you actually try to use what's available in C++ to do it. I'd look up std::max_element to find the largest element in the input, and use an std::vector instead of messing with dynamic allocation directly.
When you want the number of elements in an array in C++, you might consider a function template something like this:
template <class T, size_t N>
size_t num_elements(T const (&x)[N]) {
return N;
}
Instead of dumping everything into main, I'd also write the counting sort as a separate function (or, better, a function template, but I'll leave that alone for now).
// warning: Untested code:
void counting_sort(int *input, size_t num_elements) {
size_t max = *std::max_element(input, input+num_elements);
// allocate space for the counts.
// automatically initializes contents to 0
std::vector<size_t> counts(max+1);
// do the counting sort itself.
for (int i=0; i<num_elements; i++)
++counts[input[i]];
// write out the result.
for (int i=0; i<counts.size(); i++)
// also consider `std::fill_n` here.
for (int j=0; j<counts[i]; j++)
std::cout << i << "\t";
}
int main() {
int a[]={2,3,1,2,3};
counting_sort(a, num_elements(a));
return 0;
}