21-day learning-through C++_DAY6

Source: Internet
Author: User

0. Pointers & Arrays

An array is a pointer to its first element, which is a pointer to an array variable. The (*) can be used for arrays, or ([]) for pointers, eg:

int mynums[5] = {0};

int* pnums = mynums;

You can use * (mynums+1), or you can use pnums[1].

1. Points to note when using the pointer

① Be sure to initialize the pointer variable to NULL;

② to verify that the pointer is valid before use ( check if null);

③new and delete to match, otherwise it will cause memory leaks ;

2, check whether the allocation request issued by new is satisfied

Method one: Using exception handling, catch (Bad_alloc)

1#include"stdafx.h"2#include <iostream>3 using namespacestd;4 5 intMain ()6 {7     Try8     {9         int* PAge =New int[536870911];Ten         Delete[] pAge; One     } A     Catch(bad_alloc) -     { -cout<<"error!"<<Endl; the     } -  -     return 0; -}

Law II: New (Nothrow)

1#include"stdafx.h"2#include <iostream>3 using namespacestd;4 5 intMain ()6 {7     8     int* PAge = New(nothrow) int[536870911];9     if(PAge)Ten     { One         Delete[] pAge; A     } -     Else -cout<<"error!"<<Endl; the  -     return 0; -}

3. Reference = = Alias

Reference, you can access the memory unit of the corresponding variable .

21-day learning-through C++_DAY6

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.