Pointers (new and delete)

This is a discussion on Pointers (new and delete) within the C++ Programming forums, part of the General Programming Boards category; Hi, i've just been working through the pointers chapter in my C++ book and come across a confusing part. What's ...

  1. #1
    Registered User
    Join Date
    Aug 2002
    Posts
    1

    Question Pointers (new and delete)

    Hi, i've just been working through the pointers chapter in my C++ book and come across a confusing part.

    What's the difference between using:

    int iAge = 20;
    int * pAge = &iAge;

    and

    int * pAge = new int;
    *pAge = 20;

    i.e. Why use new and delete when you can just make a pointer like the first method?

  2. #2
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,786

    Re: Pointers (new and delete)

    Originally posted by Russ
    Hi, i've just been working through the pointers chapter in my C++ book and come across a confusing part.

    What's the difference between using:

    int iAge = 20;
    int * pAge = &iAge;

    and

    int * pAge = new int;
    *pAge = 20;

    i.e. Why use new and delete when you can just make a pointer like the first method?
    With the first method, your creating a variable on the stack.....this only has a fixed amount of memory.....so say at runtime you needed an amount of ints, but you didnt know how many, youd be stumped as you would be stuck to 1 int.....with the second method you can have as many ints as you choose

    int * pAge = new int(20);

  3. #3
    Registered User
    Join Date
    Aug 2002
    Posts
    5

    Pointers

    See, when u use the following

    int iAge = 20;
    int * pAge = &iAge;

    u r first creating a variable named iage. As pointers can store memory addresses so the pointer pAge is storing the memory address of the iAge.

    Now in the latter

    int * pAge = new int;
    *pAge = 20;
    Here,
    U r creating a new memory location that will be pointed by pAge.

    In the first case,
    If u change the valueof iAge to 30 then u 'll find that
    the value of *pAge also becomes 30.

    In the latter case,
    The value of *pAge can be changed only by :
    *pAge=30;

    Consult a book 4 betterment of concepts.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21