1

So I'm creating an empty array and assigning to its first 4 elements some values. I'm copying the same code into Visual Studio and the program doesn't work because it can't understand the line. So how in C++ declare empty arrays?

#include <iostream>
using namespace std;

double inTotal(double quartersQuantity, double dimesQuantity, double 
nickelsQuantity, double penniesQuantity) {


double total = 0.25 * quartersQuantity + 0.10 * dimesQuantity + 0.05 * 
nickelsQuantity + 0.01 * penniesQuantity;

return total;

}

int main(int argc, const char * argv[]) {

string coinNames[] = {"quarters", "dimes", "nickels", "pennies"};
double coinQuantity[] = {};
int counter = 0;

for (string values : coinNames) {
    cout << "How many " << values << " do you have\n";
    cin >> coinQuantity[counter];
    counter++;

}

double total = inTotal(coinQuantity[0], coinQuantity[1], 
coinQuantity[2], coinQuantity[3]);
cout << "Your dollar value is " << total << " dollars." << endl;



return 0;
}

enter image description here

3
  • 1
    The code you show is invalid: there is no such thing as a non-dynamic zero size array in standard C++. When you use a language extension that allows it, you have Undefined Behavior by using any item, as you do. Instead of raw arrays just use std::vector, which can expand as needed when you use e.g. v.push_back( blah );. Apr 5, 2018 at 3:39
  • SO but how come the program in xCode works fine?
    – Tigran
    Apr 5, 2018 at 3:46
  • Possible UB includes that the program does what you intended. Until, by Murphy's law, it's critical that it works. Then it produces a big fat scrolling banner saying that the persons you are doing a demo for, those interested buyers, are ugly and dumb. Apr 5, 2018 at 3:50

2 Answers 2

0

You can initialise array this way.

int coinQuantity[4];  // declare the array
for (int i = 0; i < 4; i++) // ...initialize it
{
    coinQuantity[i] = 0;
}
0

So how in C++ declare empty arrays?

As "Cheers and hth. - Alf" wrote:
there is no such thing as a non-dynamic zero size array in standard C++.

But you don't actually want an empty array; in your case, you need an array coinQuantity with the same number of elements as the array coinNames has. In Visual Studio you can define it by writing

double coinQuantity[_countof(coinNames)] = {};

In environments which don't predefine the macro _countof(), you can define that by writing

#define _countof(array) (sizeof array / sizeof *array)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.