0

I'm starting out in CPP on arrays and pointers.

I'm trying to print a float array but I'm getting past the float array.

How can I stop printing the float array once i hit the end?

// all about arrays and pointers

#include <iostream>

using namespace std;

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

    float inputs1 [] = { 12 };
    float inputs2 [] = { 12 , 4 };

    cout << "sizeof(inputs1)" << sizeof(inputs1) << endl;
    cout << "sizeof(inputs2)" << sizeof(inputs2) << endl;

    float *it = inputs2;
    cout << *it << endl;
    it++;
    cout << *it << endl;
    cout << endl;

    cout << "sizeof(inputs1): " << sizeof(inputs1) << endl;
    cout << "sizeof(inputs2): " << sizeof(inputs2) << endl;
    cout << "start address: " << &inputs2 << endl;
    cout << "end address: " << &inputs2[sizeof(inputs2)] << endl;

    for (float *it2 = inputs2; it2!=&inputs2[sizeof(inputs2)]; it2++) {
        cout << "it2 " << it2 << endl;
        cout << "*it2 " << *it2 << endl;
    }
}
extensa5620
  • 681
  • 2
  • 8
  • 22

1 Answers1

4

sizeof returns the size of its argument in bytesnot the number of elements in it1.

To get the number of elements, you have to divide sizeof(inputs1) by sizeof(inputs1[0]).

1 unless the elements are one byte each, such as char

Emil Laine
  • 41,598
  • 9
  • 101
  • 157