Yesterday in my interview I was asked this question. (At that time I was highly pressurized by so many abrupt questions).
int *p;
*p=23;
printf("%d",*p);
Is there any problem with this code?
I explained him that you are trying to assign value to a pointer to whom memory is not allocated.
But the way he reacted, it was like I am wrong. Although I got the job but after that he said Mohit think about this question again. I don't know what he was trying to say. Please let me know is there any problem in my answer?
EDIT I added the code on the sheet;-
int *p;
p=malloc(sizeof(int));
*p=23;
printf("%d",*p);
This must be the perfect code...Am i right..
EDIT2
int *p;
*p=23;
OR
int *p=23;
I think both has problem. Cause some body is saying about the title of the post.
int **p declares a pointer on the stack which points to pointer(s) on the heap. Each of that pointer(s) point to an integer or array of integers on the heap.
They are the same. The first one considers p as a int * type, and the second one considers *p as an int .
int *p[10] would mean that p is an array of 10 integer pointers. 2. int(*p)[10] is basically a pointer to an array of 10 integers. The basic difference is that in case 1 the data in array will be like this: p[0]=<some address>
p is the value of p while *p is the value stored in the memory location pointed by p . When you want to indirectly access the value of an integer i , you can have an integer pointer point to it ( int *p = &i ) and use that pointer to modify the value of i indirectly ( *p = 10 ).
"trying to assign value to a pointer to whom memory is not allocated"
I think you just misphrased it a bit. You're not trying to assign a value to a pointer, you're trying to assign a value to the referand of a pointer.
Since the pointer is uninitialised, this is, as you say, undefined behaviour. The pointer doesn't refer to anything (at least not validly - as other answers point out, the bits of storage of p
might just so happen to contain a value which is the address of some memory location, and your code might overwrite that. The standard permits anything to happen with UB, but knowing something about your implementation you can often take a shrewd guess).
So probably in the interviewer's mind you have the right idea, but it's valuable to have it exactly straight in your mind and in your speech what the difference is between a finger and the moon, and which one you're talking about.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With