Mailbox #1: Pointer query

Query: What this pointer exactly holds in this case and how it works.

int *p;
p = (int *)300;

In the above assignment statement, we are storing an integer into a pointer. Since it will not be allowed directly, hence a type casting is required.
Once the assignment is done, pointer p will contain 300 and it will be interpreted as an address. Dereferencing the pointer p, will try to access an integer stored at address 300. The result will be garbage (unless you know what is stored at address 300). Also, the safe execution of the dereferencing statement will depend on the OS in which the code is executed. As under Linux the program will generate segment fault/core dump.

Read Pointer in C/C++ Part – 1 for more explanation.

Query: What is this declaration ? For this printf what will be the answer and why?

double *p,*q;
p=(double *)4000;
q=(double *)2000;

For the explanation about declaration, see the above explanation.

In the printf() we are printing the result of subtracting two pointers of the same type. The number of memory locations between the two addresses will be 4000 – 2000 = 2000bytes. Since the size of double (as both are double pointers) is 8 bytes. The result will be 2000 / 8 = 250. Hence, printf() will print 250 as the output.

Read Pointer in C/C++ Part – 2 for more explanation.

2 thoughts on “Mailbox #1: Pointer query”

  1. Hello Sir,

    I had an interview in a company named “TATA power”.
    I have some problems :

    The interviewer asked me the following Question:

    1) reverse a string without using any variable. You are not even allowed to use a variable to store a string.

    2) “C” doesnt provide boundation checking on array but it is still able to findout the length of array using the sizeof(). Why it cannot enforce boundation checking on array?

Leave a Reply

Your email address will not be published. Required fields are marked *