[C++]重新定义 y 值的基本数组代码。它正在工作,但无法解释为什么
[C++]Basic Array code that redefines y value. It's working but cannot explain why
我在网络上看到了一些代码,并试图弄清楚它是如何工作的。我试图在每行上留下评论,但我不明白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的本地变量(都指向相同的内存地址。
相关文章:
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 为什么我需要C++中不同的排序格式来对这个USACO代码上的数组和优先级队列进行排序
- 有没有一种代码密度较低的方法来使用非默认构造函数初始化数组?
- 请解释字谜的代码,我看不懂计数器数组,每个值已经是0
- 代码使用向量成功运行,但使用数组显示错误
- C++逗号分隔的输入数组代码过早退出
- 如何修改代码以打印出数组 v2
- 我正在尝试解决一个需要数组总和值但代码不起作用的问题,我想做这样的事情
- 如何在 c# 代码中通过引用调用时从 c++ dll 更新数组值?
- 使用基于数组和范围的 For 循环替换一些基本代码行
- G++ 发出警告,要求删除一个代码的数组,但不删除另一个代码的数组
- 为什么我的代码在尝试复制字符数组时引发 C6386 错误?
- 用于查找数组中最大元素的出现次数的代码,给出分段错误
- 调试代码块中的数组
- "p"数组如何使用 std::normal_distribution 存储以下代码中的值C++?
- 在带有模板的函数中传递未知大小的 std::数组.如何更正此代码?
- 有没有办法在c ++中清除空数组,请检查下面的代码以获取说明
- 我在 2D 数组的动态内存分配中遇到了一些奇怪的代码C++? 请解释一下这是什么?
- 我的旋转数组代码给出了大数组大小的错误
- 将字符数组转换为键代码数组 c++