solo learn put this question right but answer is wrong WHY SOLO LEARN ?? WHY? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 8

solo learn put this question right but answer is wrong WHY SOLO LEARN ?? WHY?

#include<stdio.h> #include<stdlib.h> typedef struct{ int first; float second; } data; data*makedata() { printf("%d\n",sizeof(data)); return (data*)malloc(sizeof(data)); } int main() { data* d=makedata(); d->first=21; d->second=3.14; printf("%d\n",d->first+d->second); free(d); return 0; } THIS IS QUESTION IN CHALLENGE , THEY HAVE PUT 42 IS RIGHT ANSWER BUT IN MY SYSTEM DEV C++ IT IS SHOWING ZERO AS A OUTPUT

20th May 2020, 7:46 AM
Ashutosh k.
Ashutosh k. - avatar
4 Answers
+ 4
https://code.sololearn.com/cIJ18ZHL0M4J/?ref=app I correct it. but i don't know more things about c.
20th May 2020, 8:43 AM
Eshan Gayanga
Eshan Gayanga - avatar
+ 4
see my screen shot
20th May 2020, 3:45 PM
Ashutosh k.
Ashutosh k. - avatar
+ 2
Have you run this code in sololearn codeplay yet? If not then run in sololearn codeplay and see the output... Question in challenges made by sololearn users so it has the possibility to have a wrong Answer.
20th May 2020, 8:38 AM
Aazad Waf 🌀
Aazad Waf 🌀 - avatar
+ 2
"%d" is wrong specifier for sizeof(). It returns an unsigned type (unsigned int or unsigned long/long long, depends on platform) so In C99 you should use "%zu" specifier and in C89 "%lu". there is no null-check for return of malloc(). d->second is a float ,so sum of expression will be of type float which in printf() is promoted to double. Result is 24.14 but for "%d" specifier you must cast to int which truncates value to 24. When using wrong format specifiers for your types the behavior will be undefined. There is no way it should be 42? Unless you wrote numbers in reverse order.
20th May 2020, 2:11 PM
Gen2oo
Gen2oo - avatar