3

How is the value 2 being stored since the pointer has not been initialised in the following code snippet ?

int *p;
*p = 2;
printf("%d %d\n",p,*p);

The Output for the above program is as follows :

0 2

I was reading "Expert C Programming" by Peter Linden, and found this :

float *pip = 3.141; /* Wont compile */

But then how is the above program giving an output ? Is it because of using GCC ? or am I missing something ?

EDIT

I understand why float *pip = 3.141 is not valid, since an address location has to be an integer. So does this mean that p stores the memory address '0' and the value of '2' is being assigned to this address? Why is there no segmentation fault in this case?

Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
Kyuubi
  • 1,228
  • 3
  • 18
  • 32

2 Answers2

3
float *pip = 3.141;

pip is a pointer, a pointer must be initialized with an address (not with a value)

e.g:

float f[] = {0.1f, 0.2f, 3.14f};
float *pip = &f[2];
printf("%f\n", *pip);

EDIT:

Another one:

int *p = malloc(sizeof(int)); /* allocates space */
*p = 2; /* Now you can use it */
printf("%p %d\n", (void *)p, *p);
free(p);
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
0

The line

float* pip = 3.141

can be rewritten

float* pip;
pip = 3.141;

See the difference? Compare it to:

int* p;
*p = 2;

In the former case, you're trying to assign 3.141 as a memory address, while in the latter case, you're (validly) assigning 2 as a value to the dereferenced memory address.

Andrew Cheong
  • 29,362
  • 15
  • 90
  • 145
  • i understand why pip cannot be assigned 3.141 since that is not a valid address. so does that mean p points to address '0' (is this garbage value?) and the value of '2' is being stored at this address ? – Kyuubi Jul 26 '13 at 22:53
  • `*p = 2` is potentially disastrous surely. You were just lucky that the program responded in a sensible fashion. – suspectus Jul 26 '13 at 23:17
  • Thats what I thought. But then something more shocking : http://ideone.com/hHvX1m two variables having the same address 0 ? or is there a mistake in the way i am printing the address ? – Kyuubi Jul 26 '13 at 23:19
  • 2
    @Kyuubi - You're mistaken that the address starts as 0. The behavior is undefined. See http://stackoverflow.com/questions/4285895/where-exactly-does-c-standard-say-dereferencing-an-uninitialized-pointer-is-un. – Andrew Cheong Jul 27 '13 at 00:23