Array sum is giving the wrong answer when the program is ran - c++

The program runs smoothly and I have no errors or warnings when its compiled its just when it gets the end result I just get a load of random letters and numbers no matter what I put in.
Here is the code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int hold;
int n;
int * result = new int;
int * price = new int;
std::string items[6];
for (n=0; n<6; n++)
{
cout << "Item#" << n+1 << ": ";
cin >> items[n];
}
cout << "\nYou Entered: ";
for (int n=0; n<6; n++)
cout << items[n] << ", ";
for (n=0; n<6; n++)
{
if (items[n] == "ab"){
price[n] = 2650;
}
else if (items[n] == "ae"){
price[n] = 1925;
}
else if (items[n] == "ie"){
price[n] = 3850;
}
else if (items[n] == "bt"){
price[n] = 3000;
}
else if (items[n] == "pd"){
price[n] = 2850;
}
else if (items[n] == "ga"){
price[n] = 2600;
}
}
for (n=0; n<6; n++)
{
result += price[n];
}
cout << "\nTotal gold for this build: " << result;
cin >> hold;
return 0;
}

int * price = new int;
and
int * result = new int;
allocate a single int respectively. You probably meant new int[6].
But then again, you should be using std::vector instead.
I'm disappointed really that you took no advice from - https://stackoverflow.com/a/12868164/673730 - if you had, you wouldn't have this problem now. This is not a good way to learn.

With this declaration: int * price = new int; you only allocate space for a single int, but you go on to use price as an array of int.
To declare an array, use: int *price = new int[5];
As for result, you declare that as a pointer to int also, but you later use it as an int: result += price[n];. No need to result to be a pointer. Also note that you need to initialize your variables explicitly: set result to zero before you begin using it.

just give some comments:
new operater should be used with delete.
"int *result" you declared is a point to int, so you should dereference this point to get the result you want.
exceptions should be taken into consideration, what if the input letter is not in your given list?

Well, result is an int *. This kind of variable usually stores the address of another integer variable, which you get with new int in this specific case. However, with
result += price[n];
you'll modify that address, which would lead to segmentation faults if you were to actually write/read from *result. This is also the reason why you output is strange:
cout << "\nTotal gold for this build: " << result;
This prints the adress stored in result, not the value. Make result an integer and it should work.
Please note that price should be changed too, see Luchian's answer.
Exercise
Change your code so that there is no use of new.
Your program could still fail. What is the initial value of result?
What happens if the user provides a code which is not in your list?

Change the line:
cout << "\nTotal gold for this build: " << result;
to
cout << "\nTotal gold for this build: " << *result;
Result is a pointer, so you need to dereference it, using the * operator;
Edit: Change the declaration of the price array to
int *price = new int[6];
The previous declaration declared a variable, not an array

Related

struct + functions code breaks

There is a problem with the code and i could not find it.
i was asked to write a money struct and use functions to manipulate it.
but the code did not work for any function. i tried couting
the array of structers and it came out nicely, for any missing info
please leave a comment and i'll reply shortly.
Money.txt
2
12 20
13 40
#include <iostream>
#include <fstream>
using namespace std;
struct Money { //declaring structure
int dollars;
int cents;
};
Money addMoney(Money *p[], int n) { //adds money data
Money cash{ 0,0 };
int i;
for (int j = 0; j < n; j++) {
cash.dollars = cash.dollars + p[j]->dollars;
cash.cents = cash.cents + p[j]->cents;
}
if (cash.cents >= 100) //100cents = 1 dollar
{
i = (cash.cents) / 100;
cash.dollars = cash.dollars + i;
i = (cash.cents) % 100;
cash.cents = i;
}
return cash;
}
void printMoney(Money *p[], int n) { //printing money data
for (int i = 0; i < n; i++) {
cout << "Dollars: " << p[i]->dollars << endl;
cout << "Cents: " << p[i]->cents << endl;
}
}
Money maxMoney(Money *p[], int n) {
Money cash;
cash.dollars = p[0]->dollars;
cash.cents = p[0]->cents;
for (int i = 0; i < n; i++)
{
if ((p[i]->dollars)>=(cash.dollars))
if ((p[i]->cents)>(cash.cents))
{
cash.dollars = p[i]->dollars;
cash.cents = p[i]->cents;
}
}
return cash;
}
void main() {
Money cash;
ifstream mycin("money.txt");
if (mycin.fail())
cout << "Enable to open file";
int x;
mycin >> x;
Money *arr = new Money[x];
for (int i = 0; i < x; i++)
{
mycin >> arr[i].dollars;
mycin >> arr[i].cents;
}
cout << "The values in money.txt are: ";
printMoney(&arr, x);
cash = addMoney(&arr, x);
cout << "These values added are :";
cout << cash.dollars << " Dollars and " << cash.cents << " cents" << endl;
cash = maxMoney(&arr, x);
cout << "Maximum value is :";
cout << cash.dollars << " Dollars and " << cash.cents << " cents" << endl;
}
These functions appear to accept an array of pointers to Money, but you're trying to use them with an array of Money.
I suggest you play with arrays of pointers to simpler types (like int) until you're comfortable with the concept, before you attempt it with Money.
This sounds a lot like homework so I'm not posting a full solution, but I will explain what appears to be the misunderstanding and give you some pointers.
First you declare your data structure as an array of Money structures, e.g. a continuous series of blocks of memory containing the Money struct, the first of which is pointed to by "arr" in your main program.
But then, in the rest of the program (functions) you seem to expect the data structure being used to be an array of Money pointers. See the difference? They're not the same and this will not work as is. You have to be consistent.
Either you're dealing with an array of structs, in which case you pass effectively a single, simple Money* to your functions everywhere (and you dereference with . not ->)
Or you're dealing with an array of pointers, in which case you pass effectively a pointer to a (Money pointer) and you dereference with -> as you've done. But then you also have to allocate each Money struct individually when you're reading them in in the main program. That is to say, allocating memory for the array of pointers does not automatically allocate memory for each Money pointer reference in the array of pointers and so you need to do this for each entry you're reading in.
So, as you should hopefully now realise, there's multiple ways to fix your program.
As per your later comment, given that the function signatures need to stay as-is, I would suggest you work with an array of Money pointers.
Money** arr = new Money*[x]
Then you need to add a line to your loop during reading, to actually make each Money * point to a Money struct:
for (int i = 0; i < x; i++)
{
arr[i] = new Money
...
Finally then, because "arr" is now a pointer to a pointer to Money, you can directly pass it to your functions, so calling them are just for example:
printMoney(arr, x);

Console crashes outputting pointer array and iterations C++

I am busy working on a simple concept to display pointer arrays and iterations of a for loop in C++
My compiler is not giving much away and when I run the program the console is saying the following and returning 3 "The application has requested the Runtime to terminate in an unusual way.
The crash occurs on this line:
cout << i + 1 << " " << *(pArray + i) << endl;
but when I run this program ommiting either i + 1 or *(pArray + i) it runs without errors or crashing.
Is it illegal to try and output as I am trying to do above?
See below for the code:
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
int * pArray;
int SIZE;
int module;
pArray = new int[SIZE];
cout <<"Enter the number of Assignments ";
cin >> SIZE;
cout <<"input assignment number " ;
for (int i = 0; i < SIZE; i++)
{
cin >> module;
*(pArray + i) = module;
}
// Print array
for (int i = 0; i < SIZE; i++)
{
cout << i + 1 << " " << *(pArray + i) << endl;
}
cout << endl;
delete[] pArray; // Deallocate array via delete[] operator
return 0;
}
I am admittedly a little nervous to ask this question but I just need someone to explain why this is happening as I am battling to find any reference on this type of situation.
Thanks
You use SIZE two lines before you initialize it.
Move
pArray = new int[SIZE];
to after where you obtain the value of SIZE.
(Also: this would be so much easier with std::vector.)
int * pArray;
int SIZE;
int module;
pArray = new int[SIZE];
SIZE is not initialised yet, so, it would be some junk value.
Initialise it before using it.
You could also Check for success/failure of new.
pArray = new(nothrow) int[SIZE];
if(pArray)
//logic

segmentation fault with dynamic allocation and arrays/pointers

I'm working on an assignment that is introducing the principals of dynamic allocation of memory and pointers. I had made a simple program in the past that accepted 5 names and 5 scores and then used a selection sort to put them in descending order. My assignment now is to come back to that same program and ask the user how many scores they would like to input, then use pointers to dynamically allocate the necessary amount of memory. This is my first time working with pointers and these concepts so im still trying to figure it all out.
I got the code to compile but I get a segmentation fault error as soon as i enter any integer number for how many scores i would like to input (which is the first thing the program asks)
Im sure there are a few errors along the way with how i called and declared functions so if theres anything i just desperately change please let me know, but for now I dont understand why my program is crashing where it is crashing.
Here is my code
#include <iostream>
using namespace std;
void initializeData(string *names[], int *scores[], int num);
void displayData(string *names[], int *scores[], int num);
void sortData(string *names[], int *scores[], int num);
int main()
{
int num;
int **intPoint;
string **strPoint;
cout << "How many scores would you like to enter?: ";
cin >> num;
cout << " core dumped? ";
*intPoint = new int[num];
*strPoint = new string[num];
initializeData(strPoint,intPoint,num);
sortData(strPoint,intPoint,num);
displayData(strPoint,intPoint,num);
return 0;
}
void initializeData(string *names[], int *scores[], int num)
{
for(int i=0;i<num;i++)
{
cout << "Please input the name for score: " << i+1 << ": " << endl;
cin >> *(names[i]);
cout << "Please input the score for player: " << i+1 << ": " << endl;
cin >> *(scores[i]);
}
}
void sortData(string *names[], int *scores[], int num)
{
int minIndex,minValue,x;
string stringTemp;
for(int i = 0;i<(num-1);i++)
{
minIndex = i;
minValue = *(scores[i]);
for(x= i+1;x<num;x++)
{
if(*(scores[x]) > minValue)
{
minValue = *(scores[x]);
minIndex = x;
}
}
*(scores[minIndex])=*(scores[i]);
*(scores[i]) = minValue;
stringTemp = *(names[minIndex]);
*(names[minIndex]) = *(names[i]);
*(names[i]) = stringTemp;
}
}
void displayData(string *names[], int *scores[], int num)
{
cout << "Top scorers: " << endl;
for(int i=0;i<num;i++)
{
cout << names[i] <<": ";
cout << scores[i] << endl;
}
}
and my current output:
How many scores would you like to enter?: 10
Segmentation fault (core dumped)
which happens regardless of what int i put there. I put a cout statement after the
cin << num; to see if the program got that far but it never does.
Any help is greatly appreciated. Sorry if this is the most basic error ever.
int **intPoint;
At this point in your code, intPoint doesn't point to anything since you haven't assigned it a value.
*intPoint = new int[num];
Then you dereference it, but it doesn't point to anything.
Try:
int *intPoint;
intPoint = new int[num];
Now you are setting intPoint's value so that it points to the integers you allocated.
The reason you get a segmentation fault is because you dereference an uninitialized pointer.
int **intPoint; // intPoint is declared a pointer to a 'pointer to an int';
// but currently it points to nothing
*intPoint = new int[num]; // *intPoint "dereferences" intPoint, i.e., assigns w/e it
// pointed to (which is nothing) to a pointer.
Like the others have suggested, you didn't need a double pointer here.
int *intPoint; // intPoint is a pointer to an int
intPoint = new int[num]; // notice how we didn't dereference intPoint.
// all we did was assign to our newly minted memory.
Use std::vector in the place of array of int or string.
say,
std::vector<int> scores;
std::vector<string> names;
This way you can avoid all the hassles. This is simple and elegant.

I'm getting a weird error for a program that seems like it should "just work."

I present to you all a program I'm working on for my college programming course. I still have a little ways to go before it completely meets my assignment's requirements, but I've gotten a basic draft of the program error-free (supposedly) and it appears to run… but then it suddenly kicks me into Xcode's debugger and gives me:
Thread 1: EXC_BAD_ACCESS(code=2, address=0x7fff95c1e5f5)
Here's the command line output, up until it kicks me out:
-----------------------
Quarterly_sales_taxator
-----------------------
How many company divisions will we be dealing with? 2
Am I correct in assuming that there are 4 sales quarters? yes
Please enter the sales Company Division #1 brought in for Sales Quarter #1 20
(lldb)
Here's my code:
//
// quarterly_sales_taxator.cpp
// Ch. 7 program #7
//
// Created by John Doe on 11/27/12.
//
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
#include <cctype>
using namespace std;
void read_company_divisions_and_sales_quarters(double **, int, int);
//void write_company_divisions_and_sales_quarters_to_array(double **, int, int); // This will be used later on to read data from a file.
void display_quarterly_sales_array(double **, int, int);
string temp; // A global temporary placeholder variable; I use this several times.
int main()
{
int COMPANY_DIVISIONS,
SALES_QUARTERS = 4;
double **quarterly_sales_form;
cout << "\n\n-----------------------\nQuarterly_sales_taxator\n-----------------------\n\n";
cout << "\nHow many company divisions will we be dealing with? ";
getline(cin, temp);
stringstream(temp)>>COMPANY_DIVISIONS;
while (COMPANY_DIVISIONS < 1 || isdigit(COMPANY_DIVISIONS == false))
{
cout << "\n\n------"
<< "\nError:"
<< "\n------"
<< "\n\nYou have entered an invalid choice."
<< "\nPlease type a number greater than zero. ";
getline(cin, temp);
stringstream(temp)>>COMPANY_DIVISIONS;
}
cout << "\n\nAm I correct in assuming that there are 4 sales quarters? ";
getline(cin, temp);
// Convert to uppercase.
for (int count = 0; count < temp.length(); count ++)
{
temp[count] = toupper(temp[count]);
}
if (temp == "NO" || temp == "NOPE" || temp == "INCORRECT" || temp == "YOU ARE NOT" || temp == "YOU ARE INCORRECT" || temp == "NEGATIVE" || temp == "NEGATORY")
{
cout << "\nOk, then how many sales quarters are we dealing with? ";
getline(cin, temp);
stringstream(temp)>>SALES_QUARTERS;
}
cout << endl << endl;
// This sets up the 2d array.
quarterly_sales_form = new double *[COMPANY_DIVISIONS];
for (int count = 0; count < COMPANY_DIVISIONS; count ++)
{ quarterly_sales_form[COMPANY_DIVISIONS] = new double [SALES_QUARTERS]; }
read_company_divisions_and_sales_quarters(quarterly_sales_form, COMPANY_DIVISIONS, SALES_QUARTERS);
// write_company_divisions_and_sales_quarters_to_array(quarterly_sales_form, COMPANY_DIVISIONS, SALES_QUARTERS); // I'll add this feature later.
cout << "\n\nHere's what you entered:\n\n";
display_quarterly_sales_array(quarterly_sales_form, COMPANY_DIVISIONS, SALES_QUARTERS);
// Since we used a series of pointers, we need to free the allocated space back up.
for (int count = 0; count < COMPANY_DIVISIONS; count ++)
{ delete[] quarterly_sales_form[COMPANY_DIVISIONS]; }
delete[] quarterly_sales_form;
return 0;
}
/*############################################
# read_company_divisions_and_sales_quarters #
############################################*/
void read_company_divisions_and_sales_quarters(double **array, int DIVISIONS, int QUARTERS)
{
for (int count = 0; count < QUARTERS; count++)
{
for (int index = 0; index < DIVISIONS; index++)
{
cout << "\nPlease enter the sales Company Division #" << count+1 << " brought in for Sales Quarter #" << index+1 << " ";
getline(cin, temp);
stringstream(temp) >> array[count][index];
}
}
}
/*################################
# display_quarterly_sales_array #
#################################*/
void display_quarterly_sales_array(double **array, int DIVISIONS, int QUARTERS)
{
for (int count = 0; count < DIVISIONS; count++)
{
cout << "\nCompany division #" << count+1 << ":\n";
for (int index = 0; index < QUARTERS; index++)
{ cout << array[count][index] << ", "; }
}
}
Can some kind soul please tell me what I'm doing wrong?
{ quarterly_sales_form[COMPANY_DIVISIONS] = new double [SALES_QUARTERS]; }
In this line, COMPANY_DIVISIONS should be count.
In addition to what Dan Hulme said, it seems this line
stringstream(temp) >> array[count][index];
should really be
std::istringstream(temp) >> std::skipws >> array[index][count];
In addition to using std::istringstream rather than std::stringstream and making sure that an lvalue is at hand, which isn't strictly needed until the type read becomes more interesting, this also reverses the indices: index runs over COMPANY_DIVISIONS and count over SALES_QUARTERS.
The real question is, of course: Who hands out assignments like this? Pointer manipulations and allocations are best left to low-level library writers. This is C++ not C: we can and should use abstractions. Getting this code exception safe is a major challenge and there is no point in teaching people how to write broken (e.g. exception unsafe) code.

Comparison with string literal results in unspecified behaviour?

I am having a problem with the program I am trying to code. It's just a Windows console program and I am very new to C++. It's only my 4th program.
The problem I am having is that when I run my program I have no errors but a lot of warnings that say "comparison with string literal results in unspecified behaviour" in the lines that I will highlight below.
When the program runs instead of adding the numbers I want it to it just gives me a random huge number no matter what I put in for my inputs.
Here is the code:
#include <iostream>
using namespace std;
int main()
{
int hold;
int i;
int n;
i = 6;
int result;
int * price;
char items[100][100];
if (items == 0)
cout << "No items can be stored";
else
{
for (n=0; n<i; n++)
{
cout << "Item#" << n << ": ";
cin >> items[n];
}
cout << "\nYou Entered: \n";
for (n=0; n<i; n++)
cout << items[n] << ", ";
}
for (n=0; n<i; n++)
{
if (items[n] == "ab"){
price[n] = 2650;
}
else if (items[n] == "ae"){
price[n] = 1925;
}
else if (items[n] == "ie"){
price[n] = 3850;
}
else if (items[n] == "bt"){
price[n] = 3000;
}
else if (items[n] == "pd"){
price[n] = 2850;
}
else if (items[n] == "ga"){
price[n] = 2600;
}
}
for (n=0; n<i; n++)
{
result = result + price[n];
}
cout << "\nTotal gold for this build: " << result;
cin >> hold;
return 0;
}
Any help is appreciated. There is probably something big that I've done wrong. The names in the if statements are all currently placeholders and I'll be adding a lot more if statements when I can get it to work with the bare 6 which is what it needs to work.
In C++ == only implemented internally for primitive types and array is not a primitive type, so comparing char[100] and string literal will only compare them as 2 char* or better to say as 2 pointers and since this 2 pointers can't be equal then items[n] == "ae" can never be true, instead of this you should either use std::string to hold string as:
std::string items[100];
// initialize items
if( items[n] == "ae" ) ...
or you should use strcmp to compare strings, but remeber strcmp return 0 for equal strings, so your code will be as:
char items[100][100];
// initialize items
if( strcmp(items[n], "ae") == 0 ) ...
And one extra note is if (items == 0) is useless, since items allocated on stack and not in the heap!
First, int * price; is a dangling pointer - you never initialize it. You have to do:
int * price = new int[i];
Second, usually, i denotes an iterator index so I suggest you stick with that - so
for (i=0; i<n; i++) //some more refactoring needed
Third, you need to compare char arrays using strncmp in your case.
Fourth and most important - use std::string and std::vector instead. This is C++, not C.
Just a little thing that got me stumbling for a bit, is the difference between single and double quotes, see: Single quotes vs. double quotes in C or C++
I was comparing the first character of a string with double quotes and not single quotes - which resulted in above's error message.
You're comparing pointers, not the actual strings. Use C++ string class instead of char* (or check how C strings work).