1,217 views
0 votes
0 votes

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+=(sizeof(int)))-2;
    printf("%s",*ptr1);
}

Assume size of int pointer 4B.What will be output?

1 Answer

Best answer
1 votes
1 votes

$\rightarrow$When string constants are created then they are allocated a random memory space and all string constants end with '\0'.

$\rightarrow$So here the string constants are not allocated contiguous memory locations. First string constants are created at random memory locations and then that memory locations are pointed by array elements.

$\rightarrow$When we write like

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

$\rightarrow$Then each $arr[i]$ will point to their respective string constant's first char's location.


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

$\rightarrow$We are assigning array of string constants to a character pointer named $arr$

$\rightarrow$and not to an array of character pointers

$\rightarrow$so this constant char pointer($arr$) will just point to the first char of string constant named  "GATE" among the given string constants and the rest of the string constants will not be allocated any pointer.

G A T E \0

$\rightarrow$$arr$ points to memory location at which G is stored (say $1000$)

call(arr); // passes 1000 to **ptr

void call(char **ptr){ //ptr contains 1000.
    char **ptr1;       // a pointer which will point to address of a char pointer.
    ptr1=(ptr+=(sizeof(int)))-2; // lets decode it step by step.

$\rightarrow$ptr+=(sizeof(int)) $\Rightarrow$ ptr = ptr + 4 = 2000 + 4*(size of ptr) = 2000 + 4*8 =2032

$\rightarrow$here if size of int = 4 so sizeof(int) returns 4.

$\rightarrow$But we dont know size of $ptr$ so it will point at some random memory location.(I am assuming that $ptr$ takes 8 B.)

NOTE :- $ptr$ is not pointer to char. It is pointer to a char pointer.

$\rightarrow$(ptr+=(sizeof(int)))-2 $\Rightarrow$ ptr = ptr - 2 = 2032 - 2*8 = 2016.

ptr1 = (ptr+=(sizeof(int)))-2; // ptr1 points to address 2016.
printf("%s",*ptr1); //prints some garbage value.
selected by

Related questions

4 votes
4 votes
3 answers
1
2 votes
2 votes
2 answers
3
srestha asked May 12, 2019
1,075 views
Consider the following function $foo()$void foo(int n){ if(n<=0) printf("Bye"); else{ printf("Hi"); foo(n-3); printf("Hi"); foo(n-1); } }Let $P(n)$ represent recurrence r...