0

Recently, I encountered a problem about using the address of an array when I need to pass it as a reference to another function in C++. For example:

void do_something(float * arr, int size) {
    //Will do something about the arr
}

int main () {
    float array[] = {1, 2, 3, 4};
    do_something(array, 4);  // this will work well
    do_something(&array, 4); // this will cause error
    return 0;
}

But when I try to print out both array and &array, they are the same. Do you guys know what is the reason for this?

Han M
  • 389
  • 4
  • 14
  • That's because the type of `&array` is `float (*)[4]`. If you're learning C++, learn C++ and use the Standard Library: `std::vector` is the answer here. – tadman Feb 15 '17 at 22:04
  • As I know if you pass an `array` you are already passing an address of the array and if you pass `&array` you are passing the address of the array address – Selim Ajimi Feb 15 '17 at 22:04

1 Answers1

1

Here's a way of doing it with std::vector:

#include <vector>

void do_something(const std::vector<float>& arr) {
  // Use arr for whatever.
}

int main() {
   std::vector<float> arr = { 1, 2, 3, 4 };

   do_something(arr);

    return 0;
}

This initializer requires C++11 mode, which most compilers support if that flag is turned on.

tadman
  • 208,517
  • 23
  • 234
  • 262