37 votes

Consider the following C program

#include<stdio.h> int main() { static int a[] = {10, 20, 30, 40, 50}; static int *p[] = {a, a+3, a+4, a+1, a+2}; int **ptr = p; ptr++; printf("%d%d", ptr-p, **ptr); }

The output of the program is _______.

47 votes

Best answer

4

when a pointer is subtracted from another pointer it gives the no of memory blocks between them. ptr is P[1] and p is P[0]. hence Pr-p=1

1

Sir, please verify

if we need to find ptr+p and type of p is char;

then ptr+p = $\frac{address(ptr)+address(p)))}{size(*p)}=\frac{5}{1}=5$

Also one more doubt, if the type is **int **then pointer operations should be divisible by size of variables? otherwise it is invalid?

2

This is an excerpt from the above link:

p-q //If p and q are pointers p-q will work as above and thus will return the no. of objects of type of p (p and q must be of same data type or else it is compilation error)

I don't understand the statement (will return the number of objects of type of p). What does "type" of p mean? How can I make multiple number of objects of type p such that on doing p-q I get a number other than 1?

0

@Anil Khatri @Salman @Shaik Masthan Pls explain

**i****nt **ptr = p should store the address of complete array (say 3000)**

on incrementing ptr , the value in the ptr should get incremented to 3000+5*2 = 3010 (considering int of 2 bytes)

pls tell me where i am getting wrong or in which case the address of complete array get stored.

1

first learn the concept of array clearly, then automatically you can understood this question.

it may help you https://gateoverflow.in/282711/madeeasy-programming-language-2019?show=282720#c282720

0

@Shaik Masthan how the size of the pointer is 2 here? or if it is not then what size of the pointer should be taken?

14 votes

for ptr-p =1, as pointer increment adds the size of the data type and pointer subtraction gives the number of objects that can be held in between the two addresses = diff(addr1, addr2)/ sizeof(data type)

and for **ptr = *(a+3) = a[3] = 40

and for **ptr = *(a+3) = a[3] = 40

4 votes

0 votes

In Layman's terms:

ptr-p = location of the block where ptr points - location of the block where p points.

ptr and p point to neighbouring cells, hence their difference is 1.

You can also see that as subtracting indices, which works in all the cases.

ptr points to index 1, and p points to index 0.

Now, dereference ptr twice.

ptr » a+3 » 40

So, * 140*.