开启辅助访问 天气与日历 切换到宽版

 找回密码
 立即注册

微信帐号登录

简单一步,快速登陆

QQ登录

只需一步,快速开始

搜索
热搜: 活动 交友 discuz
查看: 2105|回复: 1

数组名不可自增与自减

[复制链接]

16

主题

31

回帖

233

积分

管理员

积分
233
发表于 2024-1-11 22:33:03 | 显示全部楼层 |阅读模式 美国
#include <iostream>

int main() {
    using namespace std;
    double wages[3] = { 10000.0, 20000.0, 30000.0 };
    double* pw =  wages;
    cout << "pw = " << pw << ", *pw = " << *pw << endl;
    pw = pw + 1;
    cout << "pw + 1 = " << pw << ", *(pw + 1) = " << *pw << endl;
    cout << "wages + 1 = " << wages + 1 << ", *(wages + 1) = " << *(wages + 1) << endl;
    //wages = wages + 1;  // invalid, because wages is a const pointer
    cout << "wages = " << wages << ", *wages = " << *wages << endl;

    return 0;
}

Yes, in C++, the name of an array is essentially a constant pointer to the first element of the array. This means that while the contents of the array can be modified, the pointer itself (i.e., the address it holds) cannot be changed.

This is why the line wages = wages + 1; is commented out in your code and noted as invalid. If you try to compile this line, you would get a compilation error because you're trying to change the address that wages points to, which is not allowed.

However, you can create a separate pointer variable and assign it the address of the array (or the address of the first element of the array), and then you can increment or decrement that pointer variable. This is what's happening with the pw pointer in your code.

Here's the relevant part of your code:

double* pw =  wages; // pw is a pointer to the first element of wages
cout << "pw = " << pw << ", *pw = " << *pw << endl;
pw = pw + 1; // incrementing pw is allowed
cout << "pw + 1 = " << pw << ", *(pw + 1) = " << *pw << endl;

In this code, pw is a pointer that initially points to the first element of the wages array. The line pw = pw + 1; increments the pointer to point to the next element in the array. This is allowed because pw is a separate pointer variable, not the array name itself.

回复

使用道具 举报

16

主题

31

回帖

233

积分

管理员

积分
233
 楼主| 发表于 2024-1-11 22:42:29 | 显示全部楼层 美国
Output:
pw = 0x7ffcc524b510, *pw = 10000
pw + 1 = 0x7ffcc524b518, *(pw + 1) = 20000
wages + 1 = 0x7ffcc524b518, *(wages + 1) = 20000
wages = 0x7ffcc524b510, *wages = 10000
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋| 怪异的C语言

GMT+8, 2024-10-1 19:20 Powered by Discuz! X3.5