指针与数组元素的地址混淆

Pointers messing with the address of array elements

本文关键字:地址 数组元素 指针      更新时间:2023-10-16

好的,首先让我提供两个程序:

程序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年ff40

ptr:
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;
}
输出:

输入数组的元素:1 2 3 4 5

*ptr: 12345

,(我):
0018年ff30
0018年ff34
0018年ff38
0018年ff3c
0018年ff40

ptr:
0018年ff30
0018年ff34
0018年ff38
0018年ff3c
0018年ff40

从上面的程序中,我们可以看到*ptr在两种情况下显示相同的输出。

我知道程序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)

好吧,我先澄清一件事。

对指针进行自增操作并没有错。自增指针与迭代器背后的概念相同,在现有代码中被广泛使用。