909 views
2 votes
2 votes

Can someone explain the output of this code? and what (char*) is doing actually?

#include<stdio.h>
struct Ournode{
    char x, y, z;
};
int main() {
    struct Ournode p={'1', '0', 'a'+2};
    struct Ournode *q=&p;
    printf("%c, %c", '*((char*)q+1)', '*((char*)q+2)');
    return 0;
}

2 Answers

1 votes
1 votes
printf("%c, %c", '*((char*)q+1)', '*((char*)q+2)');

In this line '*((char*)q+1)' is a constant since it is marked in ' ' and since %c is used it will only take the last character from the constant and print it.

So output is coming ),).

This line has no link to the structure part or pointer concept given  in the program.

For eg :-

printf("%c", '*satbir');

This will give r as output.


What is char* doing ?

(char*)q → typecasting the address into char type.

edited by
0 votes
0 votes
Cosidering ' ' in '*((char*)q+1)' and '*((char*)q+2)') :: the output will be ),)

because the whole content written inside single qoute is treated as character constant and the last character is printed.

If taking single quotes as mistake then the output will be 0,c

because q is pointing the first index of p i.e,pointing to '1' and thus q+1 will point to'0' and q+2 will point to 'a'+2 which is equal to 'c'

thus by typecasting,output will be 0,c

Related questions

0 votes
0 votes
1 answer
1
Ashish Roy 1 asked Apr 11, 2019
579 views
X=2;Y=++x * ++x * ++x ;Printf("%d",Y);In the above question, we have to use the final value of x or it will be evaluated seperately and then multiplied.Ex: Y= 3*4*5; or Y...
0 votes
0 votes
0 answers
4