Reputation: 1004
Why is that when I entered;
char string[10^4];
scanf("%s", string);
I got a runtime error and this;
char string[10000];
scanf("%s", string);
worked fine?
Btw, both worked fine when the input was not a large string. For example, when the string was "abc"
, it worked fine in both cases but when it was "wqrjljowspxmsvkjkkogvcyheydhikggaypnjdkbvhnpcxyojowhquouuuceeimgicurheuenjtritfshbbyxpsrlwxpfjwpnsjxwdbjnxaxqhryisyhkqavnxnuillwdutzywkntkkmtckbuikga"
, it worked for only the second case.
Forgive my extremely long string. it is part of my test case.
Upvotes: 0
Views: 107
Reputation: 754900
The value of 10^4
is 14 because the ^
is the XOR operator.
You can't simply write 1E4 which is 104 because that's a floating point constant and array bounds must be integer constants. You could cast it (char string[(int)1E4];
), but why not just write clearly and concisely what you mean: char string[10000];
as you did in the second example.
There's an argument that you should write:
if (scanf("%9999s", string) != 1)
…handle input error or EOF…
This protects you from a buffer overflow.
Upvotes: 7
Reputation: 45694
char string[10^4];
The above is an array of length 14, because ^
is bitwise-exclusive-or, not power.
All else is the same as for the second case, though with much lower ceiling.
char string[10000];
scanf("%s", string);
The above has 3 points-of-failure:
malloc()
, or static buffers).Upvotes: 4