指针与数组

/*
 * pointArray.cpp
 *
 *  Created on: 2016年7月21日
 *      Author: zroad
 */
#include<iostream>
#include<string>
using namespace std;

//数组初始化1
string b[4] = {"a", "b", "c", "d"};

//数组初始化2
/*
 * 未初始化数据规则:
1、在函数体外定义的内置数组,其元素均初始化为 0;
2、在函数体内定义的内置数组,其元素无初始化;
3、不管数组在哪里定义,如果其元素为类类型,则自动调用该类的默认构造函数进行初始化;
4、如果该类没有默认构造函数,则必须为该数组的元素提供显式初始化
 */
double c[4];

void pointArray() {
    //数组与指针:数组a是一个指针,且为常量,a的值为数组第一个元素的地址
    //a不可以做重新赋值等操作
    int a[5] = {100,1,2,3,4};
    cout << "a=" << a << endl;
    cout << "*a=" << *a << endl;
    cout << a[0] << endl;
    cout << a[1] << endl;
    cout << a[2] << endl;
    cout << a[3] << endl;
    cout << a[4] << endl;
    cout << "++++++++++++++++++++++++" << endl;

    //通过指针访问数组元素
    //a+i表示a的下i个元素的地址
    for(int i = 0; i < 5;i++) {
        cout << "a[" << i << "]=" << *(a+i) << endl;
    }

    cout << "==========================" << endl;
    //定义动态数组
    int n = 20;
    int *p = new int[n];
    for(int i = 0; i < n;i++) {
        *(p+i) = i+n;
        cout << "*(p+" << i << ")=" << *(p+i) << endl;
    }

    //通过new关键字定义的动态数组,最后必须使用delete关键字释放内存
    delete [] p;
}

int main() {
    pointArray();
    for (int j = 0; j < 4; j++)
        cout << b[j] << endl;
    cout << "-------------------------" << endl;

    for (int k = 0; k <4; k++)
        cout << c[k] << endl;
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值