Hi i'm a beginner in c++, recently i found out there's legal and illegal array practice. i wanted to know if this code here is illegal or legal.
i have a display of 1-5 with arr[5] ={5,5,5,5,5} and the user will input a location, the location input eg: 1 then the array will be arr[0] since it start with 0..
If the user inputs 5, line 10 will access arr[5] which is illegal. Can you explain a bit more carefully what you are trying to do? Your code doesn't seem to match up to your explanation of what you want.
umm if the user input 5, line 10 will access arr[4] sry that was typo and im sorry if this is abit confusing..i cut up abit of my original code to have a more simpler code since i wanted to know if its illegal or not only..
So you're changing the value of the input - 1 index (remember we count from 0 in C++) and adding...what to the other values? Is (10+5) supposed to be (10+1)?
You can do that with a little loop. You already know where that loop has to start.
Hint: the user gave it to you
#include <iostream>
int main()
{
constint N = 5 ;
int array[5] { 3, 5, 4, 2, 0 } ;
// print out the contents of the array
for( int value : array ) std::cout << value << ' ' ;
std::cout << '\n' ;
int location_chosen_by_user = 3 ; // one-based
constint actual_loc = location_chosen_by_user - 1 ; // zero-based
if( actual_loc > 0 && actual_loc < N ) // if within bounds of the array
{
int seed = array[actual_loc] ; // save the seed
array[actual_loc] = 0 ; // aet item to zero
for( int i = actual_loc + 1 ; i < N ; ++i ) // for the remaining positions
{
++array[i] ; // add one to the element
--seed ; // and reduce seed by one
}
// at the end, if the user did not choose the last location,
// add the residue left over in seed to the last location
if( location_chosen_by_user != N ) array[N-1] += seed ;
}
// print out the contents of the modified array
for( int value : array ) std::cout << value << ' ' ;
std::cout << '\n' ;
}
If the number of elements in the array is N, arr[i] is fine if i >= 0 && i < N,
otherwise it is undefined behaviour. The valid positions in the array are 0 to N-1, inclusive.
arr[location-1] is fine if and only if location >= 1 && location <= N. arr[location+1] is fine if and only if location >= -1 && location <= (N-2).
Rather than the smoke and mirrors approach of picking up a snippet here and snippet there the best way is to get a comprehensive understanding of arrays as a fundamental building block and spend a half an hour or so with a tutorial like http://www.cplusplus.com/doc/tutorial/arrays/
Straight away the pictorial demonstrations show how memory is set out and all the other aspects and beyond.