0
float deposit (float balance)
{
    float amount[3]; 
    system("cls");
    cout<<"Enter the amount you wish to deposit"<<endl; 
    cin>>amount[3]; 
        balance = balance + amount[3]; 
    writeBalance(balance); 
    return balance;  
}
//This is a function to allow the user to increase their balance 

but when I enter an amount in the deposit section of the program a popup box comes up and says:

Run-Time Check Failure #2 - Stack around the variable 'amount' was corrupted.

any help would be great thanks

Stefano Sanfilippo
  • 32,265
  • 7
  • 79
  • 80
user3257023
  • 43
  • 1
  • 10
  • C++ Arrays are zero-based. amount[0], amount[1], amount[2] are valid. – Roddy Jan 31 '14 at 11:06
  • You can only access amount[0], amount[1], and amount[2] – Hamza Jan 31 '14 at 11:12
  • Regarding using floating-point types for money, even `double` (or `long double`) will not help in the long run. Any arithmetic calculation (even trivial) will add compound rounding errors that sooner or later (most likely sooner) will cause major problems. You might want to read [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html). – Some programmer dude Jan 31 '14 at 11:15

2 Answers2

2

Since you have float amount[3];, you can only access amount[0], amount[1], and amount[2]. Any other index with give you undefined behaviour which is the cause of your program crash.

Also, never use a float to represent actual money. You'll only be accurate to about 7 significant figures. Using a double is unsafe too even though the accuracy (at around 15 significant figures) will be better. Your best bet is to use a currency type. Have a look at this question: Best way to store currency values in C++

Community
  • 1
  • 1
Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

You must enter each element of the array in a loop. Change the code the following way

float deposit (float balance)
{
    const size_t N = 3; 
    float amount[N]; 
    system("cls");
    cout<<"Enter the amount you wish to deposit"<<endl;

    for ( size_t i = 0; i < N; i++ )
    { 
        cin>>amount[i]; 
        balance = balance + amount[i];
    }

    writeBalance(balance); 
    return balance;  
}

Though in fact there is no need to use the array. You could enter data in one regular variable.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335