문제

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?

도움이 되었습니까?

해결책

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);

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top