指针--类型组合

来源:互联网 发布:多文件上传java 编辑:程序博客网 时间:2024/05/16 09:55

结构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