0

If I do the following code, why will f1 print out 0 to 9 normally, but f2 not? Can't you access and use dynamically and statically allocated arrays the same way since C++ arrays are a pointer to the first element?

void showFloatArray(float f1[10]) {
    for (int i=0; i < 10; i++)
    cout << " " << f1[i];
    cout << endl;
}
float *getFloatArrayOne() {
    float *floatArray = new float[10];
    for (int i=0; i < 10; i++)
    floatArray[i] = (float) i;
    return(floatArray);
}
float *getFloatArrayTwo() {
    float myFloatArray[10];
    float *floatArray = myFloatArray;
    for (int i=0; i < 10; i++)
    floatArray[i] = (float) i;
    return(floatArray);
}
int main()
{
    float *f1 = getFloatArrayOne();
    float *f2 = getFloatArrayTwo();
    showFloatArray(f1);
    showFloatArray(f2);
}
Tommy K
  • 1,759
  • 3
  • 28
  • 51
  • 2
    Turn up the warning level on your compiler, you are writing bad code. – Hans Passant Sep 30 '14 at 21:43
  • Also, pedantically speaking, C++ arrays are their own type (not a pointer), but *decay* to a pointer to their first element when required. – Cameron Sep 30 '14 at 21:44
  • Also: use `std::vector` instead of low-level arrays in almost all cases. Here you do a `new[]` without a corresponding `delete[]`. Vectors retain length information, can do some bounds checking for you, and manage the underlying memory such that their destructors will clean up for you. And in C++11 and above, they can use "move construction" to be returned from functions without paying the cost of a copy. [don't use C-style casts](http://stackoverflow.com/questions/1609163/what-is-the-difference-between-static-cast-and-c-style-casting), return isn't a function, and endl isn't the same as `\n` – HostileFork says dont trust SE Sep 30 '14 at 21:49

0 Answers0