0

Can anyone explain this question?

#include <stdio.h> int main() { char str[]="hellow\0rl\0"; printf("%d", sizeof(str)); printf("%s", str); return 0; } After null terminator why the size is counting

24th Aug 2019, 10:33 AM
Preity
Preity - avatar
6 Respuestas
+ 4
sizeof provides the size of the data item, which is the actual size of the space which has been allocated to accommodate the data, not just the length of the string (which ends after being null terminated). Take for example: char str[39] = "test"; sizeof(str) returns 39, not 4.
24th Aug 2019, 10:37 AM
Hatsy Rei
Hatsy Rei - avatar
+ 2
Preity '\0' is only one char (so sum 10) and another '\0' is automatically added at the end, so the sum is 11
24th Aug 2019, 10:50 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 2
++a || b++ is evaluated as such a is incremented, then tested. It is different from 0 so the or operator evaluate as true and does not evaluate what comes next (b++) so after that, a == 2, b == 1 and c == 1 Then the && operation b is evaluated as 1 then decremented and a is decremented then evaluated as 1 so d == 1 So the output should be 1 1 0 1
24th Aug 2019, 11:51 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 1
Baptiste E. Prunier Hatsy Rei thanks And how this is calculated can you please explain me #include <stdio.h> int main() { int a=1, b=1; int c= ++a || b++; int d = b-- && --a; printf("%d %d %d %d", d, c ,b ,a); return 0; }
24th Aug 2019, 10:52 AM
Preity
Preity - avatar
+ 1
Preity you must see why this is calculated like this in C okay forget about C think about age old logic gates truth table for a OR gate i.e. logic OR 1,0 is 1 0,1 is 1 0,0 is 0 1,1 is 1 so u see as its OR it needs only 1 input to be true to get whole output as true.. now when in C you do z = r && t if r is true we dont need to see what t is.. t will only be checked if r is false that is why.. if for 3 variable a,b,c you wish to compute a=b || c and then increment both b and c its NOT A LEGIT PRACTICE TO DO a= b++ || c++ cause if b was true i.e 1 c wont get incremented at all.. for and case think about AND gate if one input is 0 no requirement to see other... so if b is false i.e. 0 in a=b++ && c++ c won't get incremented.. Ultimately ITS NOT AT ALL A GOOD PRACTICE TO DO INCREMENT, DECREMENT AND LOGICAL AND-OR IN ONE STATEMENT JUST TO KEEP IT SHORT.
24th Aug 2019, 1:59 PM
sayan chandra
sayan chandra - avatar
0
So in my code 11 is returning so does it remove the last null character as total Is 12
24th Aug 2019, 10:41 AM
Preity
Preity - avatar