#include <stdio.h>
int *pPointer;
void SomeFunction()
{
int nNumber;
nNumber = 25;
// make pPointer point to nNumber:
pPointer = &nNumber;
}
void main()
{
SomeFunction(); // make pPointer point to something
cout<< "Value of *pPointer: "<< *pPointer <<endl;
}
You never initalize the pointer to a nullptr? You are using a global varaible? You are using a nonstandard main function? You are not including <iostream> for cout/endl; ( though it looks like you're using #include <iostream.h> and are using visual studios )
First, there's nothing dangerous about this code since it won't compile...
In SomeFunction you set pPointer to point to a local variable nNumber. This local variable stops existing when SomeFunction returns, so that in main (whose return type should be int) when pPointer is dereferenced the result is undefined behavior.
thanks guys for the fast reply.
giblit i noticed that i didn't add the iostream thanks a lot.
cire .. do u mean that when the SomeFunction returns , the variable nNumber will be deleted so when i ask for a cout , it will return a junk ?
When any object goes out of scope it is deleted. You could declare nNumber as a static int though AFAIK. Just put the value variable in same scope as the pointer or pass the value variable as a reference.
edit here is another example:
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
int& function( void )
{
staticint i = 10;
return( i );
}
int main() {
int *ptr = &function();
std::cout << *ptr << std::endl;
}
i just moved the ( int nNumber; ) under the (int *pPointer;) so it will be existing in all running time.
what i did learn that if i write ( int *pPointer; ) here i have an uninitialized pointer and that's wrong.
what should i do about that ?
L B i did that thanks
giblit if i move the ( int nNumber; ) to under the (int *pPointer;) this will do the same job , i mean this will fix the problem right ?
cire .. do u mean that when the SomeFunction returns , the variable nNumber will be deleted so when i ask for a cout , it will return a junk ?
I meant what I said. nNumber ceases to exist as a variable when the function returns. There is no "deletion."
And since that makes pPointer an invalid pointer, dereferencing it means your program exhibits undefined behavior. Undefined behavior means any behavior your program exhibits is valid, including giving you the value you actually expected (or blowing up your computer.)