383 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 .

2 Answers

Best answer
1 votes
1 votes
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
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

Related questions

0 votes
0 votes
1 answer
1
radha gogia asked Jul 28, 2015
980 views
int * p(void) { int *x; *x=10; return (x); } We create *x, and dereference it before assigning anything to it (x). Most likely, when we are declaring something on the sta...
0 votes
0 votes
2 answers
2
radha gogia asked Aug 2, 2015
845 views
int B [3];int *p = B; // why this is wrong?int (*p)[3] = B; // why this is correct?