Skip to main content
gamedev.net
🔒 Locked

quick pointer question

Started by andyZER0 Feb 19, 2005 at 7:29 PM 8 replies 1k views
Original Post
andyZER0
andyZER0


#include <iostream>
using std::cout;
using std::endl;

int main()
{
    int *p1, *p2;
    //Alright, let's say we have two pointers.  ints for example

    p2 = new int(8); // And I decide to allocate and int in one of the pointers.
    p1 = p2; // Then I go about assigning a pointer to that pointer.

    delete p2; p2 = NULL; // Then I decide to delete it.

    cout << *p1 << endl;
    /* However, when I print the value in p1, it still prints the same data 
       I allocated in the other pointer.  How come it's able to use the data 
       that was allocated in the other pointer?  I thought I deleted it.

       Thanks in advance. */

    return 0;
}


CJH
CJH
Try writing to it.
Doggan
Doggan
Yes, the space is deallocated, but p1 still points there (dangling pointer). You only set p2 to NULL. There's no guarantee p1 should print the same data (or anything for that matter), but in this case it does.
Empirical
Empirical
What does the allocation in normal brackes mean?

I do int * pInt=new int[8]; //SQAURE brackets

If its the same shouldn't you do delete [] pInt? Could that be making a diffrence?

CJH
CJH
That's allocating an array of 8 objects.
Empirical
Empirical
So what does round brackets do? Ive just tried it and it only seems to allocate 4 bytes?
andyZER0
andyZER0
Quote:
Original post by Empirical
So what does round brackets do? Ive just tried it and it only seems to allocate 4 bytes?


it's like the int's constructor. doing an int(number) gives the int the value of the number.
Interesting Dave
Interesting Dave
like

String s = new String("Hello");

in java.
Roger that, lets run like hell!
iMalc
iMalc
A pointer is just a memory address. There's nothing stopping you from attempting to access it, or write to it, or any other random memory address for that matter. Sometimes it'll even work if you read and write it.
But sometimes it'll just crash your program horribly. You are simply entrusted to not try and use freed memory - ever.

C++ isn't like VB where it goes and checks if the object reference is valid first.
Empirical
Empirical
Quote:
Original post by andyZER0
Quote:
Original post by Empirical
So what does round brackets do? Ive just tried it and it only seems to allocate 4 bytes?


it's like the int's constructor. doing an int(number) gives the int the value of the number.


Ah I see. Its obvious now you mention it, but as I only dynamicaly allocate arrays i always use curly brackets for initalization. Never seen the above before. Usefull to know though!

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.