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

 找回密码
 立即注册

微信帐号登录

简单一步,快速登陆

QQ登录

只需一步,快速开始

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

Pointer to an array and Array of pointers

[复制链接]

16

主题

31

回帖

233

积分

管理员

积分
233
发表于 2024-1-11 23:54:55 | 显示全部楼层 |阅读模式 法国
#include <iostream>

int main() {
    using namespace std;
    double wages[3] = { 10000.0, 20000.0, 30000.0 };

    double (*ps)[3] = &wages;
    cout << "ps = " << ps << ", *ps = " << **ps << endl;
    ps = ps + 1;
    cout << "ps = " << ps << ", *ps = " << **ps << endl;

    double *ps2[3] = { &wages[0], &wages[1], &wages[2] };
    cout << "ps2 = " << ps2 << ", *ps2 = " << **ps2 << endl;
    *ps2 = *ps2 + 1;
    cout << "ps2 = " << ps2 << ", *ps2 = " << **ps2 << endl;

    double *ps3 =&wages[0];
    double *ps4 =&wages[1];
    double *ps5 =&wages[2];
    double *ps6[3] = { ps3, ps4, ps5 };
    return 0;
}

Here's the difference:

  1. Pointer to an array (ps): This is a pointer that points to an entire array, not just a single element. In your code, double (*ps)[3] = &wages; declares ps as a pointer to an array of 3 doubles. ps points to the entire wages array.
  2. Array of pointers (ps2): This is an array where each element is a pointer. It can be used to create things like an array of strings, or to dynamically allocate memory for each element in the array. In your code, double *ps2[3] = { &wages[0], &wages[1], &wages[2] }; declares ps2 as an array of 3 pointers to doubles. Each element of ps2 is a pointer to a corresponding element in the wages array.

So, the main difference is that ps (pointer to an array) points to an entire array, while ps2 (array of pointers) contains individual pointers that can point to different things.

回复

使用道具 举报

16

主题

31

回帖

233

积分

管理员

积分
233
 楼主| 发表于 2024-1-11 23:56:17 | 显示全部楼层 法国
Output:

ps = 0x7ffc7d6340b0, *ps = 10000
ps = 0x7ffc7d6340c8, *ps = 0
ps2 = 0x7ffc7d6340d0, *ps2 = 10000
ps2 = 0x7ffc7d6340d0, *ps2 = 20000
回复

使用道具 举报

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

本版积分规则

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

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