retagged by
3,114 views
7 votes
7 votes

​​​Consider the following $\mathrm{C}$ function definition.

int f X(char * a) {

char * b =  a;

while (*b)

b ++;

return b - a; }

Which of the following statements is/are TRUE?

  1. The function call $\text{f X("a b c d''}$) will always return a value
  2. Assuming a character array $c$ is declared as char $c[ ]=$ "abcd" in main ( ), the function call $f X$ (c) will always return a value
  3. The code of the function will not compile
  4. Assuming a character pointer $\mathrm{C}$ is declared as char ${ }^{*} \mathrm{C}=$ "abcd" in main (), the function call $\mathrm{fX}(\mathrm{c})$ will always return a value
retagged by

3 Answers

4 votes
4 votes

Answer is A,B,D

We are modifying the local variable inside the function.

#include<stdio.h>

int fX(char *a) {

    char *b = a;

    while (*b)

        b++;

    return b - a;

}

int main(){

    

    int result_A = fX("abcd");

    printf("Option A: Result of fX(\"abcd\"): %d\n", result_A);

    

    char c[] = "abcd";

    int result_B = fX(c);

    printf("Option B: Result of fX(c): %d\n", result_B);

    char *ptr_c = "abcd";

    int result_D = fX(ptr_c);

    printf("Option D: Result of fX(ptr_c): %d\n", result_D);

    

}

0 votes
0 votes

Pointer b contains the address passed to the pointer c. Now every pointer when incremented increases it's value by the number equal to the size of data type for which it's a pointer. Also we know that the last char is followed by a null char. 

So when the b is assigned with null ptr, it breaks out of loop and returns the value of b - a. 

Note : b - a is actually the absolute address difference divided by the byte size of the data type for which it's a pointer.

So A, B, D all will always return value as the pointer will always become null ptr at some point.

Answer:

Related questions

5.0k
views
3 answers
8 votes
Arjun asked Feb 16
5,023 views
Consider the following $\text{C}$ program. Assume parameters to a function are evaluated from right to left.#include <stdio.h> int g( int p) { printf( ... $ program?$20101020$10202010$20102010$10201020$
4.1k
views
3 answers
6 votes
Arjun asked Feb 16
4,053 views
​​​​​What is the output of the following $\text{C}$ program?#include <stdio.h> int main() { double a[2]=20.0,25.0,* p,* q; p=a ; q=p+1 ; printf("%d,%d", (int) (q-p),( int)(* q- * p)); return 0;$4,8$1,5$8,5$1,8$
360
views
1 answers
6 votes
GO Classes asked Apr 24, 2022
360 views
What will be the output of the program below-int i = 1; void my_extern1(void); void my_extern2(void); int main() { int count = 0; while (i++<5) { static int i = ... (){ extern int i; if (i++ < 3) my_extern1(); }Infinite recursion$9$4$5$