C Programming - Structures, Unions, Enums - Discussion

Discussion Forum : Structures, Unions, Enums - Point Out Correct Statements (Q.No. 3)
3.
Which of the following statements correctly assigns 12 to month using pointer variable pdt?
#include<stdio.h>

    struct date
    {
        int day;
        int month;
        int year;
    };
int main()
{
    struct date d;
    struct date *pdt;
    pdt = &d;
    return 0;
}
pdt.month = 12
&pdt.month = 12
d.month = 12
pdt->month = 12
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
14 comments Page 2 of 2.

Taran rishit said:   7 years ago
(*d).month is valid I think.

Karthik said:   6 years ago
@All.

Here, It's told that assigning the value using 'pdt' variable.

So, option D is correct.

CrownedEagle said:   6 years ago
Both d.month and pdt->month will work fine.

Since d is a object of type struct date, we use '.' in d.month to access or modify value of month of object d.
whereas since pdt is pointer pointing to 'object d' we use pdt->month to access/modify the same.
Code below will print the same output regardless what operator you use.

Code:-
#include<stdio.h>
struct date
{
int day;
int month;
int year;
};

int main()
{
struct date d;
struct date *pdt;
pdt = &d;

pdt->month = 9;
printf("d.month = %d\n", d.month);
printf("pdt->month = %d\n", pdt->month);

d.month = 1;
printf("d.month = %d\n", d.month);
printf("pdt->month = %d\n", pdt->month);
return 0;

OUTPUT:-
d.month = 9
pdt->month = 9
d.month = 1
pdt->month = 1

CrownedEagle said:   6 years ago
Both d.month and pdt->month will work fine.

Since d is a object of type struct date, we use '.' in d.month to access or modify value of month of object d.
whereas since pdt is pointer pointing to 'object d' we use pdt->month to access/modify the same.
Code below will print the same output regardless what operator you use.

Code:-
#include<stdio.h>
struct date
{
int day;
int month;
int year;
};

int main()
{
struct date d;
struct date *pdt;
pdt = &d;

pdt->month = 9;
printf("d.month = %d\n", d.month);
printf("pdt->month = %d\n", pdt->month);

d.month = 1;
printf("d.month = %d\n", d.month);
printf("pdt->month = %d\n", pdt->month);
return 0;
}

OUTPUT:-
d.month = 9
pdt->month = 9
d.month = 1
pdt->month = 1


Post your comments here:

Your comments will be displayed after verification.