#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;
}
🔒 Locked
quick pointer question
Advertisement
Original Post
like
String s = new String("Hello");
in java.
String s = new String("Hello");
in java.
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.
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.
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.
Advertisement