Cpp pointers

The pointer can record an address in the main memory of the function.

The object name access the memory directly, as the name of the object is relate to some place of the memory, the pointer can store the address of the object. Then with the asterisk '*' you can access the memory with the type the pointer defined to be.

When you declare a pointer you must point it to an address, and the address must be used in the program.

You can make a space for the pointer with the keyword "new". And after the pointer have done with the memory it points, which you initialized with the keyword "new", you need to release the memory with the keyword "delete".

When using a pointer, two objects are involved: the pointer itself and the object pointed to. This means there are two possible layers of protection that we might want to impose with const:

    If we want to make sure that ptr cannot point to any other memory location, we can write it one of two ways:

    Type* const ptr = &vbl;
    Type* const ptr(&vbl);


    The pointer is a const but the addressed object can be changed.

    If we want to make sure that the value of vbl cannot be changed by dereferencing ptr, we can write it in two ways:

    const Type* ptr = &vbl;  
    const Type* ptr(&vbl);


    In this case, the addressed object is a constant but the pointer is not.

    In addition, if we want to impose both kinds of protection we can write:

    const Type* const ptr = &vbl;
    const Type* const ptr(&vbl);


    Here is a good way to remember which is which: Read each of the following definitions from right to left (starting with the defined variable).

    const char * x = &p; /* x is a pointer to const char*/
    char * const y = &q; /* y is a const pointer to char */  
    const char * const z = &r; /* z is a const pointer to a const char */

The keyword "const" is used to mark "char" or "*", like the char * if the const mark the char, like this const char * then the char is constant when accessed by the pointer, but the address where the pointer points can be changed.

When the '*' is marked with 'const', like this char * const y = & a, then the pointer can't be changed, the pointer can only point to one address.

If you want a totally constant pointer, then the pointer become to a constant, like const char * const y.

And if an address is valued to a const char pointer, then the address can't be assigned to a unconst char pointer.

转载于:https://www.cnblogs.com/henyihanwobushi/archive/2012/09/21/2697531.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值