Re: [Dev-C++] Question about pointers (beginner)
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: <or...@vp...> - 2003-05-27 19:34:13
|
Christian Schmidt wrote:
> Given x = 123 and ptr_int = &x after that *ptr_int = 456 has been executed.
> What is the value of x?
If I implemented this, this is how I would do it:
#include <stdio.h>
main()
{
int x, *ptr_int;
x = 123; /* Given x = 123 */
ptr_int = &x; /* and ptr_int =&x */
*ptr_int = 456; /* after that *ptr_int = 456 has been executed */
printf("%d",x); /* What is the value of x? */
/* The answer is: 123 */
}
> This is how I see it:
>
> main ( )
> {
> int x, *ptr_int;
>
> *ptr_int = 456; /*This pointer is a null pointer at this moment right? */
>
> x =123;
> ptr_int = &x; /* As x is just set to 123 and the statement *ptr_int = 456;
> was executed before I would think *ptr_int would be 123 */
>
> }
This is a *wrong* implementation of the example. The book does not state
this. It states what I wrote above.
And the reason why it does not segfault is only luck. *ptr_int is not
NULL at the beginning! Variables are NOT initialised, it is up to you to
do that. *ptr_int just points to somewhere, and you only had luck, that
using it didn't cause any trouble. Try setting ptr_int to NULL before
you dereference it (*ptr_int). It will surely segfault then.
You should always keep it in mind, that variables are NEVER initialised
to a default value! You must have to do that!
> But the books says the value of *ptr_int at the end is 456. How come??
The book is correct.
--
Greetings,
Balázs
|