2

I have the following:

typedef struct node{
  long long int data; 
  struct node *next; 
}node; 

However, when I tried to store a big number like:

long long int finalVal =139752196320796;
node *newNode = (node*)malloc(sizeof(node)); 
newNode->data = finalVal; 
newNode->next = NULL; 

I try to print out the value of the node and get:

-1744523748

Any tips as to why this happens?

Carlos Romero
  • 181
  • 1
  • 13

1 Answers1

2

Maybe you are printing your value as an integer using %d or %i. Instead try using the ll long long modifier i.e. %lld or lli.

printf("%lld", newNode->data);
printf("%lli", newNode->data);
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • I think that an incorrect format is probably the problem, after thinking about it. The constant should be treated as a `long long` automatically by the compiler. What the OP sees is what you get if you use `printf("%d\n", (int)newNode->data);` (and you might get the result without the cast on a little-endian machine). The main moral is "make sure you treat types correctly", and the secondary one is "make sure you compile with compiler warnings so such problems are spotted — and get a better compiler if it doesn't spot the problem". – Jonathan Leffler Mar 01 '18 at 02:30
  • @JonathanLeffler so it's not a duplicate after all! I just tested, and compiler is smart enough to add LL by itself. So printing is probably the issue. Maybe we should reopen, but it should be flagged as "unclear" or "no mcve" immediately after, or maybe there's another dupe for this. – Jean-François Fabre Mar 01 '18 at 02:45
  • (and your answer & my comment were wrong). You learn something everyday on SO XOR you get rep :) – Jean-François Fabre Mar 01 '18 at 02:46
  • note that this format doesn't work too well on windows / generates warnings unless certain options are set. But that's probably the issue. – Jean-François Fabre Mar 01 '18 at 08:59
  • @Jean-FrançoisFabre the format works well on windows. It is not an OS issue, but a compiler one. – chux - Reinstate Monica Mar 01 '18 at 13:52
  • yes, I mean: with gcc believing that Windows cannot handle the format – Jean-François Fabre Mar 01 '18 at 14:02