C++ initialized array last value is random [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I have searched on this a lot, and have not found any satisfactory response. I am codding a small mathematical algorithm in order to learn a few programming languages, and as such, this is part of my first C++ program. However, I can't seem to fix this array. Although people say random values in arrays are due to the arrays being uninitialized, and that you should initialize them to the value you want like so: int array[sizeOf] = {0}, it only sort of works in this example. Here as you can see, all values of the array get set to 0, exept the very last one, which does not seem to be getting initialized: what is causing this, and how can I fix it?
#include <iostream>
using namespace std;
int initialNumber;
int main()
{
cout << "Enter Range value:" << endl;
cin >> initialNumber; //get size
cout << "Solving..." << endl << endl;
//initialize basic ints to be used for calculations
int limiter = initialNumber/2; //the max value we will ever have to multiply by
int arraySize = initialNumber++; //size of the array
int resultingFactorsArray[arraySize] = {0}; //main array
//print each array item value
for (int x = 0; x <= arraySize; x++) {
cout << resultingFactorsArray[x] << endl; //print all array values
//all values printed should be 0, but the last one is uninitialized
}
}

Arrays are 0 based. Meaning, in your for loop, for (int x = 0; x <= arraySize; x++), the part x <= arraySize should be x < arraySize.
An example:
If you declare your array size 10, the valid array indices are 0,1,2,3,4,5,6,7,8,9 (10 total indices).
If you were to throw that in a for loop with x <= 10, your last index would be array[10] (undefined/uninitialized).
So in short, your initialization is correct, it just that your for loop is going out of bounds.

Related

Garbage value in an array where array length and input is defined [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 months ago.
Improve this question
I am a beginner, and I am trying to learn C++.
For now, all I am trying to do is input 3 numbers, and print them back.
#include <iostream>
using namespace std;
int main(){
int n[2];
cout << "Enter three numbers" << endl;
for (int j = 0; j <= 2; j++){
cin >> n[j];
}
cout << "Debug " << n[2] << endl;
cout << endl;
for (int i = 0; i <= 2; i++){
cout << n[i] << "\t" << i << endl;
}
return 0;
}
Every time I print them, the last value of the array is modified, and I cannot figure out why! For a test input 6,7,8, the output is in the image below.
This for
for (int j=0;j<=2;j++){
cin>>n[j];
}
expects that the array has at least three elements with indices in the range [0, 2].
However you declared an array with two elements
int n[2];
If you are going to input three elements then the array should be defined as
int n[3];

C++: How do I assign a value from a 2D dynamic array to another 2D dynamic array since 'temp[0][0] = array[0][0]' doesn't work? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I'm new to c++, and I'm trying to figure out how to get a 2D dynamic array called temp to get values from another 2D dynamic array called array. I couldn't figure out how to assign any values from array to temp because the statement 'temp[0][0] = array[0][0];' doesn't seem to assign the value of array[0][0] which is 1 to temp[0][0]. Instead, temp[0][0] seems to have the same random number in it after 'temp[0][0] = array[0][0]' before any value was assign to temp[0][0]. I tried to assign temp[0][0] to 2 and it works. I don't really know how to exactly assign values from one 2d dynamic array to another. Anyway thanks in advance for helping me out!
...
//initializing first 2D dynamic array
int x=2;
int y=2;
int** array = new int*[x];
for(int i=0; i<x; i++) array[i] = new int[y];
//initializing second 2D dynamic array
int new_x=3;
int new_y=3;
int** temp = new int*[new_x];
for(int i=0; i<new_x; i++) temp[i] = new int[new_y];
//assigning values
array[0][0] = 1;
cout << array[0][0] << endl; //output is 1
//before assigning values to temp[0][0]
cout << temp[0][0] << endl; //out is a huge random number
temp[0][0] = array[0][0];
cout << temp[0][0] << endl; //output is the same huge random number
temp[0][0] = 2;
cout << temp[0][0] << endl; //output is 2
...
Memory under temp[0][0] is allocated dynamically, therefore that's why you're getting some random (garbage) stuff out of it before assigning 2. When you're assigning 2, the random garbage that's been there gets "overwritten" by a meaningful value, in your case 2 of int type
The code snippet you posted works exaclty as it should:
First cout prints 1 witch is the value of array[0][0].
Second cout prints the uninitialized temp[0][0], I compiled it here, and in this case the value is 0, but it could be anything.
Third cout prints 1 due to the assingment temp[0][0] = array[0][0].
Fourth cout prints the value of 2 assigned to temp[0][0].
If there are problems in your code it's not in the posted bit, aside from the fact that you are trying to print an unitialized variable in the second cout
I have tried running the code,and the output indeed is 1 after assigning the value.

c++ input array of char after input int [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I have an array of characters with variable size which is received from user input. From there I input the array with for loop based on the size but it seems like the variable holding the size is changing and I'm stuck in infinite loop.
char arr_1[] = {};
int array_size;
cout << "Array size: ";
cin >> array_size;
for (int i = 0; i < array_size; i++)
{
cout << "Input: ";
cin >> arr_1[i];
}
I have an array of characters with variable size
char arr_1[] = {};
There is no such thing as "array with variable size" in C++. The size of an array never changes. Furthermore the size of non-dynamic arrays must be compile time constant. What you have declared there is an array of size zero. Non-dynamic arrays of zero size are ill-formed.
If the compiler for some reason fails to spot the bug (perhaps it supports zero length arrays as a language extension), then you end up accessing the array outside of bounds. The behaviour of accessing an array out of bounds is undefined. Infinite loop is one example of undefined behaviour.
There is however a standard container that will automatically reallocate a progressively larger array as you insert elements into it: std::vector.
Although, since you're dealing with characters, perhaps they're supposed to represent a character string. There is a special container for that purpose: std::string.
Vector would be more appropriate to use than an array in this case. Even easier is to just work with a string:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int numChars = 0;
string word("");
cout << "Num chars you want to input: ";
cin >> numChars;
for (int i = 0; i != numChars; ++i)
{
string input("");
cout << "Enter a char: ";
cin >> input;
if (input.size() == 1)
word += input;
else
{
cout << "Invalid input- exiting";
getchar();
exit(0);
}
}
cout << "Your word: " << word;
getchar();
getchar();
}

I keep getting the same answer, no matter what I put in [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
We're doing an assignment in my computer science class that requires us to find the future value of an investment after "n" number of years that the user inputs. It's written in C++. This is the code as I have it now:
#include <iostream>
using namespace std;
int main() {
int P=1000;
int i=0.0275;
int FV;
int n;
cout << "enter number of years:"<< endl;
cin >> n;
cout << "the future value is:"<< endl;
FV = P*(1+(i*n));
cout << FV << endl;
return 0;
}
I keep ending up with an answer of 1000 no matter what "n" I input. Can someone tell me what's wrong with the code?
#include <iostream>
using namespace std;
int main() {
int P=1000;
float i=0.0275; //float instead of int
float FV; //FV should also be float as it will be storing decimal values
int n;
cout << "enter number of years:"<< endl;
cin >> n;
cout << "the future value is:"<< endl;
FV = P*(1+(i*n));
cout << FV << endl;
return 0;
}
the mistake you have done is the type you assigned to your variables! as int only handles integer values i becomes 0 and your result becomes 1000! use float instead of int for numbers with decimal points!
Datatype of i is int as a result of which your floating point value of i will be rounded of to 0 and you will end up getting the same output doesn't matter what your n value is. Change the datatype of your i and FV varaiable from int to float then your output changes based on what n value you key in

std::sort function not working in char array [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
i was extracting lowercase and uppercase characters from a string . then print those uppercase and lowercase string in sorted order in .to sort the string i used std::sort function .but it's not working.
here is my code
#include <bits/stdc++.h>
using namespace std;
int main() {
//std::ios::sync_with_stdio(false);
char str[1005];
char low[1005];
char upr[1005];
int n;
int t;
cin>>t;
while(t--)
{
cin>>n;
cin>>str;
low[0]='\0';
upr[0]='\0';
int i=0,j=0,k=0;
while(i<n)
{
(str[i]>='A' && str[i]<='Z') ? (upr[j]=str[i],++j) : (low[k]=str[i],++k) ;
++i;
}
low[j]='\0';
upr[k]='\0';
cout<<"lowercase="<<low<<'\n';
cout<<"uppercase="<<upr<<'\n';
sort(low,low+j);
sort(upr,upr+k);
cout<<"lowercase="<<low<<'\n';
cout<<"uppercase="<<upr<<'\n';
}
return 0;
}
test case:
1 // number of test cases
15 // length of string
abHJUdjKIpwlaKm
output:
lowercase=abdjpw //before sorting
uppercase=HJUKIK //before sorting
lowercase=abdjpw //after sorting
uppercase= //after sorting
after sorting uppercase string don't even print.
You have a bug with indexes, fix:
low[k] = '\0';
upr[j] = '\0';
cout << "lowercase=" << low << '\n';
cout << "uppercase=" << upr << '\n';
sort(low, low + k);
sort(upr, upr + j);
cout << "lowercase=" << low << '\n';
cout << "uppercase=" << upr << '\n';
Exchanged k and j in this snippet.
Better variable names would help. Try replacing j and k with something more descriptive like lowIndex and uprIndex. Then you should see the problem.
I noticed you were using j variable for uppercase and k for lowercase in the while loop then proceeded to do the opposite later. Was this intentional? Wondering if that's causing a bug.