指针与数组元素的地址混淆
Pointers messing with the address of array elements
好的,首先让我提供两个程序:
程序1:#include <iostream>
using namespace std;
int main()
{
int a[5], i;
int *ptr;
ptr = a;
cout << "Enter the elements of the array:" << endl;
for (i = 0; i < 5; i++)
{
cin >> a[i];
}
cout << endl;
cout << "*ptr:";
for ( i=0 ; i<5 ; i++ )
{
cout << *ptr ;
*ptr++ ;
}
cout << "&a[i]:" << endl ;
for (i = 0; i < 5; i++)
{
cout << &a[i] << endl;
}
cout << endl ;
cout << "ptr:" << endl;
for (i = 0; i < 5; i++)
{
cout << (ptr+i) << endl;
}
return 0;
}
输出:输入数组的元素:1 2 3 4 5
*ptr: 12345,(我):
0018年ff30
0018年ff34
0018年ff38
0018年ff3c
0018年ff40ptr:
0018年ff44
0018年ff48
0018年ff4c
0018年ff50
0018年ff54
项目2:
#include <iostream>
using namespace std;
int main()
{
int a[5], i;
int *ptr;
ptr = a;
cout << "Enter the elements of the array:" << endl;
for (i = 0; i < 5; i++)
{
cin >> a[i];
}
cout << endl;
cout << "*ptr:" << endl ;
for ( i=0 ; i<5 ; i++ )
{
cout << *(ptr+i) ;
}
cout << "&a[i]:" << endl ;
for (i = 0; i < 5; i++)
{
cout << &a[i] << endl;
}
cout << endl ;
cout << "ptr:" << endl;
for (i = 0; i < 5; i++)
{
cout << (ptr+i) << endl;
}
return 0;
}
输出:从上面的程序中,我们可以看到*ptr在两种情况下显示相同的输出。输入数组的元素:1 2 3 4 5
*ptr: 12345
,(我):
0018年ff30
0018年ff34
0018年ff38
0018年ff3c
0018年ff40ptr:
0018年ff30
0018年ff34
0018年ff38
0018年ff3c
0018年ff40
我知道程序2中的代码在处理指针时是正确的递增方式。
但是,两个程序中的ptr不相同。我很确定,在程序1中用于显示*ptr的for循环是造成这种混乱的原因。我想知道在程序1中显示*ptr的for循环中发生了什么,因为ptr受到影响。在第一个程序中,ptr
正在修改自己。
注意,*ptr++;
等于*(ptr++);
,最终等于
*ptr;
ptr++;
在最后一个for
循环中向ptr
添加i
使ptr
指向其他地方,未分配的内存位置,而不是a
的元素。这就是为什么你得到的地址和第一个程序中数组元素的地址不同。
在第一个程序中,您修改了ptr
,然后在第三个循环中向其地址添加值,而没有重置到数组的开头。
第二个循环修改ptr
的值:
for ( i=0 ; i<5 ; i++ )
{
cout << *ptr ;
*ptr++ ;
}
然后在第四个循环中向其地址添加值,而不将其重置为数组的开头。
cout << "ptr:" << endl;
for (i = 0; i < 5; i++)
{
cout << (ptr+i) << endl;
}
在每次迭代中,您只增加一个,但是每次的值都增加四个,因为一个单位增量是一个int
的大小。
循环结束后
for ( i=0 ; i<5 ; i++ )
{
cout << *ptr ;
*ptr++ ;
}
第一个程序中的PTR指向数组的最后一个元素之外,因为在循环中PTR是递增的。为了得到与第二个程序相同的结果你必须将指针重置为指向循环
之后数组的第一个元素 for ( i=0 ; i<5 ; i++ )
{
cout << *ptr ;
*ptr++ ;
}
ptr = a;
在第一个程序中,您正在更新指针(更改指针保存的地址)。因此,在循环之后,指针指向数组
的最后一个地址之外。 *ptr++ ;
在第二个程序中,你没有更新指针中包含的地址。
*(ptr+i)
好吧,我先澄清一件事。
对指针进行自增操作并没有错。自增指针与迭代器背后的概念相同,在现有代码中被广泛使用。
- 数组元素打印的递归方法
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 为什么使用数组元素查找最大数字的程序不起作用?
- 数组元素更改值?
- 如何访问宏中定义的数组元素
- 将数组元素递增 1
- C++函数,它将数组、谓词和运算符作为参数,并将运算符应用于满足谓词的数组元素
- 存储指向动态数组元素的指针
- C++通过别名指针以静默方式将错误的类型分配给数组元素
- 在 std::map 中插入数组元素
- 创建一个函数来转换数组元素的类型并返回数组的地址
- 将特定数组元素的地址传递到函数
- 数组元素值,元素地址和指针增量
- 为什么数组元素长度的地址计算可被 2 的幂整除更有效
- 相邻数组元素地址之间的差异
- C++ 更改数组元素的地址
- 如何获取数组元素的地址
- 指针与数组元素的地址混淆
- 为什么数组元素的地址有时会被误认为是声明
- 数组元素 c++ 的地址