0
What I've done wrong?
You are given an array of doubles of items in a store that have different prices (see template). Write a program that takes the "percent off" discount as input and outputs discounted item prices on one line in the same sequence you are given, separated by a space (" "). Sample Input 25 Sample Output 375 9.3 70.5 33.75 2.25 60.75 750.675 63.75 67.5 0.75 26.25 My code: include <iostream> using namespace std; int main() { double items[] = {500, 12.4, 94, 45, 3, 81, 1000.9, 85, 90, 1, 35}; //your code goes here int x; cin>>x; for(int i=0;i<sizeof(items );i++){ cout<<items [i]-items[i]*x/100<<" "; } return 0; }
3 Answers
+ 4
The sizeof() operator returns the size of its operand in bytes. For an array, that equals the number of elements multiplied by the size of a single element, so in this case 11 * sizeof( double ).
This means that in your for loop, you iterate far beyond the original array, and access it out of bounds, which is undefined behaviour.
To get the array size, you therefore need to divide the result of the sizeof() operator by the size of a single element, i.e.
sizeof( items ) / sizeof( double )
or use std::size() from the standard library.
+ 1
@Martin Taylor, the std::size() function has an overload that makes it work with plain arrays, by templating for an arbitrary type and a size constant:
https://en.cppreference.com/w/cpp/iterator/size
As far as I know, there is no possibility to only automatically size the array. You either specify both or have both deduced from the deduction guide provided for std::array:
https://en.cppreference.com/w/cpp/container/array/deduction_guides
So the declaration would be:
array nums = { 1.23, 2.34, 3.45, 4.56 };
+ 1
@Martin Taylor, the Microsoft page regarding the std:c++xx option says the following regarding /std::c++14:
"It doesn't disable some C++17 features already implemented in previous releases of the MSVC compiler. To avoid breaking changes [...], these features remain enabled when the /std:c++14 option is specified."
From:
https://docs.microsoft.com/en-gb/cpp/build/reference/std-specify-language-standard-version?view=msvc-160
The std::size() function is among those features, since it has already been available as of VS 2015, which you can see in the following table (needs some scrolling down to C++17 library features):
https://docs.microsoft.com/en-gb/cpp/overview/visual-cpp-language-conformance?view=msvc-160
Since C++14 is the default and there doesn't seem to be support for a lower version, you always have access to std::size(), regardless of the compiler flag.
Meanwhile on my local machine with GCC, I need to explicitly specify std=c++17 or std=c++20 to be able to use it.