Redirected
in Programming in C edited by
2,345 views
1 vote
1 vote
Consider the following c-program:

#include<stdio.h>

int main() {

char *arr[ ] ={"GATE", "CAT", "IES", "IAS", "PSU", "IFS" };

call(arr);

return 0;

}

void call (char **ptr) {

char **ptr1;

ptr1=(ptr+=size of (int)) -2;

printf("%s\n",*ptr1);

}

which of the following represent the output of the above program?(Assume size of int,pointer is 4B).

A)IES

B)IAS

C)CAT

D)PSU
in Programming in C edited by
2.3k views

4 Comments

Yes you can add integer to pointer, but it will not be the direct integer that will be added.

Suppose ptr++ => ptr=ptr+1 

it will calulated as ptr=address_pointing_by_ptr+ sizeof(ptr)*1 isn't this correct?

0
0
Yes, it is correct.
0
0

sizeof (char) = 1B

sizeof (int) = 4B

ptr1 = (ptr+= sizeof(int))-2;

let's solve inside () first,

(ptr+= sizeof(int))

ptr was pointing to first element of array but now incremented to 4B and now is pointing to 5th element of array which is "PSU"

so now we got,

ptr1 = (&(arr[4]))-2;

ptr1 will subtract 2B from ptr which is pointing to arr[4] and will point to arr[2]

ptr1 is pointing to arr[2] and will print "IES"

2
2

2 Answers

2 votes
2 votes
char *arr[ ] ={"GATE", "CAT", "IES", "IAS", "PSU", "IFS" };

Above is a array of character pointers.

Size of a char* = 8 bytes ( normally in a 64-bit system )

let arr = 1000, then arr +1 = 1008 and arr + 2 = 1016

ptr1=(ptr+=size of (int)) -2;

sizeof( int ) = 4

ptr += 4, ptr = ptr + 4, ptr = 1000 + (4*8); ( 8 is the size of character pointer )

ptr = 1032

ptr1 = 1032 - 2 => ptr = 1032 - (2*8) => ptr = 1016

ptr == (arr + 2)

So, 

printf("%s\n",*ptr1)

prints " IES " ( third element of the array )

2 Comments

**ptr, **ptr1 and *arr are the double pointers. The pointer arithmetic you did it is apply on the single pointer (correct me if i am wrong). in array all the element have size 5,4,4,4,4,4 byte of blocks (Note: different block size). the pointer **ptr, **ptr1 will point to these blocks. But you are taking one level up and doing calculation. How it is relate to the answer?
0
0

*arr is not double pointer it is array of pointers.

0
0
0 votes
0 votes

This is my approach to solving it please tell if I am wrong

Related questions

Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true