in Programming in C
376 views
0 votes
0 votes
int *ptr;

ptr=9 ; // this is an error

so to rectify it we write :

int *ptr=(void*)9;

why is this stmt true , what happens on type casting this 9 to a void pointer type since 9 is an integer constant .
in Programming in C
376 views

2 Answers

1 vote
1 vote
Best answer
ptr = 9; 

This is not an error. But it is not recommended to directly assign values to pointers as we cannot be sure of dereferencing them as actual memory address using * operator. 

int *ptr=(void*)9; 

This also does the same job as above. Only difference is we explicitly typecast 9 as an address which would avoid compiler warning.

So, both would work but both are to be avoided in good programming. If we need to use one, use the second one. 

NB: These kind of questions are way out of GATE scope. You can see previous GATE questions here (see the ones with GATEXXXX tags). 

selected by
by
0 votes
0 votes
segmentation fault can occur . what u are basically trying to do is assigning pointer memory address 9 which may be os protected aor not in the address space of the compiler. Only one case is possible here . u can directly set it to zero which will be considered as null . but when we assign as void pointer. it work because it is called explicit cast . explicit cast tell the compiler automaticaly make a memory address and save 17. now the complier doesn't know what type of pointer it is . so u should make it cast accordingly which is done by void pointer.
edited by