[C++]重新定义 y 值的基本数组代码。它正在工作,但无法解释为什么

[C++]Basic Array code that redefines y value. It's working but cannot explain why

本文关键字:代码 数组 工作 为什么 无法解释 新定义 C++ 定义      更新时间:2023-10-16

我在网络上看到了一些代码,并试图弄清楚它是如何工作的。我试图在每行上留下评论,但我不明白y [0]为5555。我猜y [0]可能会更改为数字[0],但是为什么呢?x值仍然是1。嗯..这是因为y[0] = 1;没有int数据类型?

#include 使用名称空间std;

void m(int, int []);
/*this code explains a variable m that m consists of two parts, int and int array*/
int main()
{
  int x = 1; /* x value is declared to 1*/
  int y[10]; /*Array y[10] is declared but value is not given*/
  y[0] = 1; /*Array y's first value is declared to 1 but data type is not given*/

  m(x, y); /*This invokes m with x and y*/
  cout << "x is " << x << endl; 
  cout << "y[0] is " << y[0] << endl;
  return 0;
}
void m(int number, int numbers[]) /*variable names in m are given, number and numbers.*/
{
  number = 1001; /*number has int 1001 value*/
  numbers[0] = 5555; /*This overrides y to numbers[], so y[0] =1 changes to numbers[0] = 5555.*/
}
/*This program displays 
 * x is 1
 * y[0] is 5005
 * y[0] value has changed but x has not.
 * */

我猜y [0]可能会更改为数字[0],但是为什么呢?x值仍然1。

请不要猜测。您的代码正常工作。

number = 1001;不会以任何方式影响 x
number是本地副本(按值通过(。

numbers腐烂到原始数组的第一个元素的指针,因此在函数范围之外更改。

好..这是因为y[0] = 1;没有INT数据类型?

否,如上所述。y[0]实际上是类型int

在这种情况下,

int numbers[]几乎等同于 int* numbers。您不是将向量作为不可变的对象传递,而是作为参考。因此,numbers(函数的本地变量(和y(MAIM的本地变量(都指向相同的内存地址。

相关文章: