PDA

View Full Version : basic C++ question



Maluko_Da_Tola
23rd August 2010, 15:19
Hi,

I am not sure if this question is appropriate for a Qt forum, since it is a general c++ question.

The following code won't compile:

int *p;
*p=7;
cout<<*p;

When I create the pointer p, the compiler assigns a random adress and a random int value for p. On the second line of code, I try to change the int value that the compiler has previously assigned for p and on the last line it should output this value. All the Qt compiler says is: 'the program has unexpectedly finished'. Any suggestions why this happens?


Thank you

Zlatomir
23rd August 2010, 15:27
When you use pointers, think of two (2) variables, one of type T and the other one that store the address of the first variable.

Your code doesn't compile because you try to dereference an uninitialized pointer:


int var;
int *p = &var; //the pointer store the address of var
*p=7; //var will have the value 7
cout<<*p;


A pointer by itself is pretty much useless, you need a variable to store the actual data. (even if the variable is allocated on the heap, and it doesn't have a name... the variable is still there)

SixDegrees
23rd August 2010, 20:25
Also, pointers need something to point at. In your original code, you declare a pointer, but you don't allocate any memory for it to point at, as in


p = new int;

Without this step, you can't assign anything to p because there is no memory to hold the value.

zeldaknight
24th August 2010, 08:29
You use the 'new' operator if you don't want to have another named variable, eg. int *p = new int;

When you create a pointer, the computer creates a space in memory to hold the address of a variable. It doesn't create any space in memory for the variable itself, if you see what I mean. You have to tell it 'create a space to hold the address of a variable AND create a space for the variable itself'. That's what new does. That's also why you wouldn't usually use 'new int' - because the computer will have allotted four bytes or whatever to hold the address of the integer you're creating. Creating the integer uses up another four bytes, meaning you are using double the memory.

Hope that helps.