指针--类型组合

2 篇文章 0 订阅

结构struct和数组与指针在一起是怎么用的呢?总是分不清数组指针和指针数组,下面就用一个例子说明这方面的知识点。

结构struct

先复习一下结构

//
//  typeCombination.cpp
//  FirstMacOSCpp
//
//  Created by Nicolas Yam on 2017/11/5.
//  Copyright © 2017年 Nicolas Yam. All rights reserved.
//

#include <iostream>
#include <string>

//结构定义
struct inflatable {
    std::string name;
    double volume;
    double price;
};

int main(int argc, const char * argv[]) {
    using namespace std;

    //结构声明与初始化
    inflatable inflate;
    inflate.name = "Glorious";
    cout << inflate.name << endl;

    //还可以创建结构数组
    inflatable inflates[2];
    inflates[0].volume = 10.24;
    cout << inflates[0].name << endl;

    //未完待续...
}

类型组合

在上一次回顾了指针的用法和一些细节后,这次来看一看指针、结构、数组的组合使用。这个例子也说明了指针数组和数组指针。

    //续...
    //类型组合
    inflatable inflate1, inflate2, inflate3;
    inflate1.price = 1998;

    //创建结构指针
    inflatable* pIn = &inflate2;
    pIn->price = 2017;

    //创建结构数组
    inflatable trio[3];
    trio[1].price = 2018;
    cout << (trio + 1) -> price << endl;

    //创建指针数组
    const inflatable* arrIn[3] = {&inflate1, &inflate2, &inflate3};
    cout << arrIn[1] -> price << endl;

    //创建数组指针
    //arrIn是数组的名称,即第一个元素地址,其第一个元素也为指针
    //因此pArrIn是指向一个指向inflatable结构的指针
    const inflatable** pArrIn = arrIn;
    //pArrIn指向arrIn第一个元素即&inflate1,加一则是第二个
    //注意这里一定要加括号,没有括号的*pArrIn -> price
    //意味着*会作用于pArrIn -> price,而price不是指针,导致错误
    cout << (*pArrIn) -> price << endl;
    cout << (*(pArrIn + 1)) -> price << endl;

    return 0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值