in Programming in C
22,442 views
61 votes
61 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 _______.

in Programming in C
22.4k views

4 Comments

Notice-> In proper answer there is no space between 1 and 40.
6
6
Please answer the following question with the help of diagram

*(*(a+3)+2)?
0
0
Little modification need in best answer.

Address in ptr should use rather than address of ptr?
1
1
10 a
20 a+1
30 a+2
40 a+3
50 a+4
…... …...
a p
a+3 p+1
a+4 p+2
a+1 p+3
a+2 p+4
…... …..
p+1 ptr

 

0
0

11 Answers

64 votes
64 votes
Best answer
static int a[] = {10, 20, 30, 40, 50};
static int *p[] = {a, a+3, a+4, a+1, a+2};
int **ptr = p;

ptr++;

$\text{ptr-p} = \frac{\text{address of ptr} - \text{address of p}}{\text{sizeof(*ptr))}} = 1$

$\text{**ptr = p[2] = *(a+3) = 40}$

printf("%d%d", ptr-p, **ptr);  // 140
edited by

4 Comments

@habedo007 the excerpt you highlighted is missing some important important words.

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 between the memory addressess of p and q (p and q must be of same data type or else it is compilation error)

p-q returns number of objects of data-type of p b/w  the two memory addresses. 

Example: p=2000, q=2012 are both pointer to integer. so now p-q will give 2000-2012= 12 bytes (-ve sign doesn’t matter here).

Let sizeof(int) = 4bytes.

so how many integer object can we have in 12bytes?

12/4=3 hence at last p-q is 3.

 

0
0

@Lakshman Patel RJIT  sir the link provided by arjun sir is not showing words with proper alignment...plz fix that if possible

0
0
wrong

Difference between two pointers from each other tells the distance in terms of number of elements (it is the valid arithematic on pointers)
0
0
37 votes
37 votes

explanation

1 comment

good xplanation!
1
1
14 votes
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

2 Comments

a[3] is 40.
1
1
here answer will be 140..(ptr-p)=(address of incremented ptr -  starting address of ptr)/sizeof(int)=1

and **ptr =40 so 140
1
1
11 votes
11 votes

 

 

 

 

 

 

 

 

 

 

 

Correct answer will be $1$ and $40$ irrespective of size of pointer and data types

reshown by
Answer:

Related questions