Node:Pointers and initialization, Next:Variable parameters, Previous:Pointer types, Up:Pointers
Pointers and initialization
You should not initialize pointers with a value when you declare them,
although the compiler will not prevent this. Doing so simply makes no
sense. For example, think about what happens in the following
int *my_int_ptr = 2;
First, the program allocates space for a pointer to an integer.
Initially, the space will contain garbage (random data).
It will not contain actual data until the pointer is "pointed at"
such data. To cause the pointer to refer to a real variable, you
need another statement, such as the following:
my_int_ptr = &my_int;
On the other hand, if you use just the single initial assignment,
int *my_int_ptr = 2;, the program will try to fill the contents
of the memory location pointed to by
my_int_ptr with the value 2.
my_int_ptr is filled with garbage, it can be any
address. This means that the value 2 might be stored anywhere.
anywhere, and if it overwrites something important,
it may cause the program to crash.
The compiler will warn you against this. Heed the warning!