简体   繁体   English

C ++中的参数和函数

[英]Parameters and functions in C++

Let's suppose this code: 我们假设这段代码:

void function(const float vect[]){

// making something with "vect" here (not modifying as it is const)

};

then in the main function: 然后在主要功能:

float v[5];

function(v+2);

Is it correct to call the function like that? 这样调用函数是否正确? What exactly I'm passing to that function doing that? 究竟我正在传递给那个功能呢?

The array will decay to pointer during the call 在调用期间,数组将衰减为指针

so you're basically doing this :- 所以你基本上是这样做的: -

+---+---+---+---+---+
|   |   |   |   |   |
+---+---+---+---+---+
 ^    ^   ^   ^   ^
 |    |   |   |   |
 v   v+1 v+2 v+3 v+4
          ^
          |
function(v+2); //In "function" v will be used from v+2, i.e. vect[0] will be v[2]

To understand this you have to understand that sometimes C++ lies. 要理解这一点,你必须明白有时C ++是谎言。

void function(const float vect[]){ is not a function taking an array as a parameter (that's the lie). void function(const float vect[]){不是将数组作为参数的函数(这就是谎言)。 Instead it's exactly the same as if you had written this void function(const float* vect){ . 相反,它与您编写此void function(const float* vect){ Now it's easier to understand, your function takes a pointer, so when you write function(v+2); 现在它更容易理解,你的函数需要一个指针,所以当你写function(v+2); you are passing a pointer to the third element of your array, just as when you write function(v); 你正在传递一个指向数组第三个元素的指针,就像你写function(v); you are passing a pointer to the first element of your array. 您正在将指针传递给数组的第一个元素。

It's impossible to pass an array to a function in C++ (or return an array from a function), arrays are always converted into pointers in these situations. 将数组传递给C ++中的函数(或从函数返回数组)是不可能的,在这些情况下,数组总是转换为指针。

Is it correct to call the function like that? 这样调用函数是否正确?

As long as you don't access the array out of bounds (ie you only read vect[0] , vect[1] or vect[2] ), it is. 只要您不访问数组越界(即您只读取vect[0]vect[1]vect[2] ),它就是。

What exactly I'm passing to that function doing that? 究竟我正在传递给那个功能呢?

I don't understand this question. 我不明白这个问题。 If you want to know what this does: the v array decays into a pointer, then the + operator performs pointer arithmetic on it, and a pointer to of the third element (ie the one at index 2) is passed to the function. 如果你想知道这是做什么的: v数组衰减成指针,然后+运算符对它执行指针运算,并且指向第三个元素的指针(即索引2处的指针)被传递给函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM