C primer plus plus 指针(2)

//

//  main.cpp

//  Pointer2

//

//  Created by 炒饭 on 2019/4/14.

//  Copyright © 2019 炒饭. All rights reserved.

//

#include <iostream>

int main()

{

    // insert code here...

    using namespace std;

    double wages[3] = {10000.0,20000.0,30000.0};

    short stacks[3] = {3,2,1};

    double *pw = wages;

    short *ps = &stacks[0];

    cout << " pw = "<< pw <<" , *pw " << *pw <<endl;

    cout << "ps = "<< ps << ", *ps "<< *ps <<endl;

    ps = ps+1;

    cout << "add 1 to the ps pointer:\n";

    cout << "ps = "<< ps <<", *ps = "<< *ps <<"\n\n";

    cout << "access two elements with array notation\n";

    cout <<"stack[0] = "<< stacks[0] <<", stack[1] = "<< stacks[1] <<endl;

    cout <<"access two elements with pointer notation \n";

    cout << "*stacks = "<< *stacks << ", *(stacks +1) = "<< *(stacks +1)<< endl;

    cout << sizeof(wages) <<" = size of wages array\n";

    cout << sizeof(pw) << " = size of pw pointer\n";

    //显示地址

    cout << wages <<endl;//display &wages[]0 8字节的内存块

    cout << &wages <<endl;//display adress of whole array 24字节的内存块

    

    //动态结构体声明

    struct inflatable

    {

        char name[20];

        float volume;

        double price;

    };

    inflatable * ps1 = new inflatable;

    cout  << "enter name of inflatavle item: ";

    cin.get(ps1->name,20);

    cout <<"Enter volume in cubic feet: ";

    cin >> (*ps1).volume;

    cout << "enter price :$";

    cin >>ps1->price;

    cout << "name: "<< (*ps1).name << endl;

    cout << "volume "<<ps1->volume <<endl;

    cout <<"price: $"<<ps1->price << endl;

    delete ps1;

    

    

    std::cout << "Hello, World!\n";

    return 0;

}

实验结果:

pw = 0x7ffeefbff550 , *pw 10000

ps = 0x7ffeefbff45c, *ps 3

add 1 to the ps pointer:

ps = 0x7ffeefbff45e, *ps = 2

access two elements with array notation

stack[0] = 3, stack[1] = 2

access two elements with pointer notation

*stacks = 3, *(stacks +1) = 2

24 = size of wages array

8 = size of pw pointer

0x7ffeefbff550

0x7ffeefbff550

enter name of inflatavle item: "zhoujian"

Enter volume in cubic feet: 50

enter price :$10.2

name: "zhoujian

volume 50

price: $10.2

Hello, World!

Program ended with exit code: 0

猜你喜欢

转载自blog.csdn.net/zjguilai/article/details/89302134