Why arrays do not print whole table? - c++

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int d,m;
int districts=3;
int months = 12;
double sales[districts][months];
for (d=0 ; d < districts; d++)
{
for(m=0; m< months; m++)
{
cout << "Enter sales for District " << d+1 << ":" << " and Month " << m+1 << ": ";
cin >> sales[districts][months];
}
}
cout << "\n\n\n";
cout << setw(40) << "Months\n";
cout << setw(26) << "1 2 3 4 5 6 7 8 9 10 11 12\n";
for (d=0; d < districts ; d++)
{
cout << "District " << d+1;
for(m=0; m< months; m++)
{
cout << ": " << sales[districts][months];
}
}
return 0;
}
This code after running takes only two input values from user and after that a window appear displaying message a problem caused the program to stop working correctly.
There are no compilation errors and I am unable to find the problem. Is there anyone who can help?

You use variables d and m as counter-variables for your loops, but inside the loops you use the maximum value for both of them (districts and months) instead of d and m.

Change this: cin >> sales[districts][months]; to this: cin >> sales[d][m];
Also, this: cout << ": " << sales[districts][months]; to this: cout << ": " << sales[d][m];.
The term sales[districts][months] refers to a particular element sales[3][12], which also happens to be out of bounds for the 2-d array.

The reading loop is repeatedly reading a value to sales[districts][months], i.e. to sales[3][12], which - since array indexing starts at zero in all dimensions, doesn't exist. That gives undefined behaviour.
The output loops are repeatedly outputting the same value, which also gives undefined behaviour.
A common symptom (but not the only possible one) of undefined behaviour is abnormal program termination - and you are seeing an example of that.
There is also the wrinkle that
int districts=3;
int months = 12;
double sales[districts][months];
involves a variable length array (VLA) which is a feature of C (from the 1999 C standard or later) but is not valid C++. If that construct works for you, your compiler supports a non-standard extension.

Related

Strange result of displaying array using increment/decrement operator in C++

#include <iostream>
using namespace std;
int main()
{
double donation[10];
int index = 0;
cout.setf(ios::fixed);
cout << "Enter sum of money for donating: ";
while (index < 10 && cin >> donation[index])
{
cout << "donation #" << 1 + index++ << ": " << donation[index] << endl;
}
return 0;
}
Result
That code couldn't display right value of donation...
I could check the mistake is '1 + index++', but I don't know why did.
Why my code using '1 + index++' has a difference with code when I use 'index++' in the next line.
Keep to the idiomatic way instead of trying to understand stranger constructions and also mixing increments with function/operator parameters should be avoided (see sequence points):
for (int index = 0; index < 10; ++index)
{
if (! std::cin >> donation[index])
break;
std::cout << "donation #" << (1 + index) << ": " << donation[index] << std::endl;
}
This should do what is expected and should be understood with some knowledge of C++. It runs at most 10 times, tries to fill input to the array and displays when the input works or stops when the input fails. The only issue would be better validation of the user input.

segmentation fault with single integer

So I'm making a class which is just an easy way to manipulate an array of a different class and perform a few operations on it (fractions if you wanted to know)
NOTE: this is my homework but I don't think this violates any kind of rule because I'm not asking how to do it, but what the issue is. However, if you would have any sort of moral dilemma with this, I'm just letting you know now.
The function uses a for loop to go through an array - but not out of array bounds, because I changed the code to not even use the array
for (int i = first - 1; i < last - 1; i++) cout << i;
and I still get a seg fault when i is 4.
In the scope of the function call, i is not a variable.
The line of output from this call is
0123
Segmentation fault
so for all I know, changing i to 4 causes the error.
Member data in the class is
private:
int size;
Fraction arr[20];
the function in the header is
Fraction Product(int first, int last) const;
and the code that uses it preceding the error is this (from Bob Myers FSU CS Dept)
http://www.cs.fsu.edu/~myers/cop3330/hw/hw4files/main.cpp
#include <iostream>
#include "flist.h"
using namespace std;
int main()
{
int start;
Fraction entry;
FList a;
cout << "Welcome!\n";
cout << a;
cout << "How many numbers to start with (1 - 20)? ";
cin >> start;
cout << "Please input the " << start << " starting fractions\n";
for (int i = 0; i < start; i++)
{
cout << "Fraction #" << (i+1) << ": ";
entry.Input();
a.Insert(entry);
}
cout << "\nHere's the list:\n" << a;
cout << "Size of list = " << a.Size() << '\n';
cout << "Sum of items in list = " << a.Sum();
cout << "\nProduct of first 5 fractions in list = " << a.Product(1,5);
I don't know much about computer organization and what's really going on behind memory allocation but I don't see how an integer can change value without changing the amount of bytes used and then become invalid memory, so I would really appreciate someone who can say I'm approaching this the wrong way.

Error when accessing array - stack around the variable 'scores' was corrupted [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 years ago.
Improve this question
I am new to C++ and have written some code in which I'm getting the following error:
Run-Time Check Failure #2 - Stack around the variable 'scores' was corrupted
What is causing this error?
Here is my code:
#include <iostream> // Enables cout and endl
#include <string>
#include <sstream>
#include "stdafx.h"
using namespace std;
int getInput();
int main()
{
int scores[5];
int i;
int j;
int numberOfScores;
for (i = 0; i < 6; i++) // Sets all 5 elements of the array to zero
{
scores[i] = 0;
}
cout << "How many scores do you have to enter?\n" << endl;
cin >> numberOfScores;
for (j = 0; j < numberOfScores; j++) // Gather test scores and increases each array index as that score is entered
{
scores[getInput()] ++;
}
cout << "The number of zeros: " << scores[0] << endl;
cout << "The number of ones: " << scores[1] << endl;
cout << "The number of twos: " << scores[2] << endl;
cout << "The number of threes: " << scores[3] << endl;
cout << "The number of fours: " << scores[4] << endl;
cout << "The number of fives: " << scores[5] << endl;
return 0;
}
int getInput()
{
int enteredScore;
cout << "Enter the test scores one at a time.\n";
cout << "The range of scores is 0 to 5.\n";
cin >> enteredScore;
if (enteredScore >= 0 && enteredScore <= 5)
{
return enteredScore;
}
else
{
cout << "Error! The range of scores is 0 to 5.\n";
cout << "Enter the test scores one at a time.\n";
cin >> enteredScore;
return enteredScore;
}
}
It seems that this declaration:
int scores[5];
Is incorrect. This creates an array with 5 numbers in it, indices from scores[0-4], however, you constantly refer to score[5], the sixth element of the array throughout your program. I recommend changing to
int scores[6];
The problem:
You are accessing your array out of bounds in several places.
Here you loop through 6 elements when you only have 5:
for (i = 0; i < 6; i++) // Loops through 6 elements
{
scores[i] = 0;
}
Here you call getInput() and use the return value as the index:
scores[getInput()] ++;
However, the first half of the function accepts inputs from the user in the range 0 to 5, thus allowing access to 6 elements:
if (enteredScore >= 0 && enteredScore <= 5)
It gets even worse if the user enters a number outside that range, as they are then given a second opportunity to enter a number, only this time there is no validation and any number they enter is accepted:
cin >> enteredScore;
return enteredScore;
Finally, you again attempt to access a 6th element here:
cout << "The number of fives: " << scores[5] << endl;
Solution:
First, you need to do one of two things:
Change the for loop, if statement, and cout statements so that they do not access index 5
or:
Create the array so that it has 6 elements: int scores[6];
Secondly, you need to fix the bug in your getInput() function so that it validates the input properly. You could try this for example:
int getInput()
{
int enteredScore;
cout << "Enter the test scores one at a time.\n";
cout << "The range of scores is 0 to 4.\n";
cin >> enteredScore;
while (enteredScore < 0 || enteredScore > 4)
{
cout << "Error! The range of scores is 0 to 4.\n";
cout << "Enter the test scores one at a time.\n";
cin >> enteredScore;
}
return enteredScore;
}
You have an error in
cout << "The number of fives: " << scores[5] << endl;
Your array is of size 5 but you are accessing the 6th element.
Same with for (i = 0; i < 6; i++) should be i < 5.

Sudoku game design problems C++

I have (yet another) question about chars. Thanks to those who helped me with this before. I'm trying to do mainly 4 things at this point in the program. That is:
Build a 2D array 9x9 and fill it with underscores.
Ask for a row/column and then the number that the user wishes to go into that row/column as many times as the user wants.
Replace the specified blanks with the specified numbers.
Output the entire 9x9 char array on an ASCII art Sudoku board.
(Solving will come later.)
My problem is that when I enter the row/column and the number that I want to go into that row/column the dash that was originally in that spot disappears, but the number I entered does not appear in its place.
Here is the code so far:
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main () {
//Builds 9x9 char array.
char dash[9][9];
for (int array=0; array<9; array++) {
for (int array2=0; array2<9; array2++) {
dash[array][array2]='_';
}
}
cout << "Input the row #, then the column #, then the number that you wish to fill that spot." << endl;
cout << "Remember that a Sudoku board is 9x9." << endl;
cout << "When you wish to finish input and solve, type all 0's and press enter." << endl;
int rowb;
char row[99];
int columnb;
char column[99];
int numb;
char num[99];
//Inputs the row/column and number to go into specified row/column.
int control=0;
while (rowb!=0){
control++;
cout << "Row: ";
cin >> rowb;
cout << "Column: ";
cin >> columnb;
cout << "Number: ";
cin >> numb;
row[control]=rowb-1;
column[control]=columnb-1;
num[control]=numb;
}
int length;
length=strlen(row);
//Replaces the _'s in the specified rows/columns and replaces them with the integer the user specified. This is where I think I'm having the problem.
for (control=0; control<length; control++) {
dash[row[control]][column[control]]=num[control];
}
//Builds the Sudoko board and outputs the full 9x9 array.
cout << "╔═══════════╦═══════════╦═══════════╗" << endl;
for (int count=0; count<3; count++) {
for (int count2=0; count2<3; count2++) {
cout << "║_" << dash[count][count2*3] << "_|_" << dash[count][count2*3+1] << "_|_" << dash[count][count2*3+2] << "_";
}
cout << "║" << endl;
}
cout << "╠═══════════╬═══════════╬═══════════╣" << endl;
for (int count=3; count<6; count++) {
for (int count2=0; count2<3; count2++) {
cout << "║_" << dash[count][count2*3] << "_|_" << dash[count][count2*3+1] << "_|_" << dash[count][count2*3+2] << "_";
}
cout << "║" << endl;
}
cout << "╠═══════════╬═══════════╬═══════════╣" << endl;
for (int count=6; count<9; count++) {
for (int count2=0; count2<3; count2++) {
cout << "║_" << dash[count][count2*3] << "_|_" << dash[count][count2*3+1] << "_|_" << dash[count][count2*3+2] << "_";
}
cout << "║" << endl;
}
cout << "╚═══════════╩═══════════╩═══════════╝" << endl;
return 0;
}
There is a problem assignment of the number entered in the loop.
//Replaces the _'s in the specified rows/columns and replaces them with the integer the user specified. This is where I think I'm having the problem.
for (control=0; control<length; control++) {
dash[row[control]][column[control]]=num[control]; //<<<--- Assignment issue.
}
You are assigning an integer value in a character array & thus when you display you will get the corresponding char for the ascii value & not the integer. Try changing the assignment as follows:
//Replaces the _'s in the specified rows/columns and replaces them with the integer the user specified. This is where I think I'm having the problem.
for (control=0; control<length; control++) {
dash[row[control]][column[control]]=num[control] + '0'; // Convert to ascii value of the integer, but will fail if not b/w 0 & 9.
}
Checking if the number entered in is between 1 & 9 is also advised if you choose to use the above observation.
Please add checks for the row & column entered as enter values which are not b/w 1 & 9 will lead to undefined behaviour due to accessing out of bound array elements if the values entered are not b/w 1 & 9.
Also as mentioned by Benjamin Lindley please update strlen code.
Hope this helps!
length=strlen(row);
This is undefined behavior, because row[0] was never initialized, and you never null terminate the string.
char row[99];
...
int control=0;
while (rowb!=0){
control++;
...
row[control]=rowb-1;
...
Notice that the first time through the loop, control is 1. So, you're setting the value of row[1], but not row[0]. Move the increment to the end of the loop. There may be some other problems, but this is the primary one responsible for the behavior you're seeing.
Also, for strlen to work, you need to null terminate the string.
And finally, you're making the same mistake you've made in this question and this question. Why aren't you seeming to get that? Chars display differently than ints. The following code will not display the number 1:
char c = 1;
std::cout << c;
Look at the answers to those other two questions.

Formatting columns in C++

I have the following program that generates a multiplication table. A formatting problem arises when the outputs reach the double digits. How do I straighten out the columns?
#include <iostream>
using namespace std ;
int main()
{
while (1 != 2)
{
int column, row, c, r, co, ro;
cout << endl ;
cout << "Enter the number of columns: " ;
cin >> column ;
cout << endl ;
cout << "Enter the number of rows: " ;
cin >> row ;
cout << endl ;
int temp[column] ;
c = 1 ;
r = 1 ;
for(ro = 1; ro < row ; ro ++ ){
for(co = 1; co < column ; co ++ ){
c = c ++ ;
r = r ++ ;
temp [c]= co * ro;
cout << temp[c] << " ";
}
cout << endl ;
}
system("pause");
}
}
C++ had setw and setfill for just this purpose. setw sets the width and setfill sets the fill character.
In your case, you can just use something like:
#include <iostream>
#include <iomanip>
int main (void) {
std::cout << std::setw(5) << 7 << std::endl; // will output " 7".
return 0;
}
You have a number of other problems with that code, at least some of which are listed below:
You don't allocate enough space for your array, it should be column*row (or use a two-dimensional array).
Array indexes start at 0, not 1.
c = c++ is not a good idea, c++ will be enough to increment c.
You may be trying to increment c twice in each iteration, once if the for statement itself and once in the for body.
system("pause"); is an ugly hack where the language provides a perfectly good getchar or cin equivalent.
while (1 != 2) just looks plain wrong :-) since 1 will never equal 2. Just use while (1) or for(;;) - any coder worth their salt will know what you mean.
use the setw output manipulator:
cout << setw(3) << temp[c];
By default, this uses spaces to fill, which it looks like you want.
You will need to include iomanip as the documentation says.
You can set width of your column elements by using stream manipulators like this:
cout << setw(3) << temp[c]
But this is something you need to fix besides: c = c++; does not increment the variable!
This is one of those situations where the old-fashioned printf is a lot easier than cout. Replace cout << temp[c] << " " with printf("%2d ", temp[c]).
And I hope you've discovered the bug in your c calculation.
You could use "\t" instead of " ".