C++ &array和array的用法有什么区别?

C++ What is the difference between the usage of &array and array?

本文关键字:array 什么 区别 C++ 用法      更新时间:2023-10-16

最近,当我需要将其传递给C 中的另一个函数时,我遇到了使用数组地址的问题。例如:

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;
}

但是,当我尝试同时打印出数组和Amp;数组时,它们是相同的。你们知道这样做的原因是什么?

这是一种使用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;
}

此初始化器需要C 11模式,如果该标志已打开,大多数编译器都支持。