retagged by
565 views
3 votes
3 votes

What does the following program print?

#include<stdio.h>
#include<string.h>
struct MdbRec {
    char name[16];
    char msg[24];
};
int main()
{
    struct MdbRec m[1];
    strcpy(m[0].name, "dude");
    strcpy(m[0].msg, "0");

    if(m == m->name)
        printf("%d", m->msg - (char *)m );
}
  1. Prints nothing
  2. Prints $17$
  3. Prints $24$
  4. Prints $16$
retagged by

1 Answer

5 votes
5 votes

Logical structure of MdbRec in Memory – 

  • sizeof( struct MdbRec ) = sizeof(name) + sizeof(msg) = 16 + 24 = 40 B (Considering sizeof(char) = 1B).
  • Suppose a variable of struct MdbRec m1 starts from location 1000.
  • Then m1.name starts from 1000 also ie m1.name[0] is at 1000, m1.name[1] is at 1001, m1.name[2] is at 1002, upto m1.name[15] is at 1015.
  • Then m1.msg starts from 1016 ie m1.msg[0] is at 1016, m1.msg[1] is at 1017, m1.msg[2] is at 1018, upto m1.msg[23] is at 1039.

In the condition (m == m→name).

  • Here, m whenever used in any expression behaves as a pointer to 1st element of array m.
  • And, m→name whenever used in any expression behaves as a pointer to 1st element of array name of the element of array m pointed by m ie 1st element of array m.
  • Since, name[ ] is the first member of struct MdbRec, both addresses pointed by m and m->name will be same.

Thus, the condition evaluates to True.

(pointer arithmetic, supose m starts from address 1000) m→msg – (char *) m = (1000 + 16 – (char *) 1000) / sizeof(char) = 16 / 1 = 16.


(counting elements) m→msg – (char *) m $\implies$ to reach first element of m→msg from start of m we’ve to skip 16 chars which are part of m→name.

Answer :- 16.

Answer:

Related questions