Manuel
Manuel

Reputation: 1004

The length of a string

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

Answers (2)

Jonathan Leffler
Jonathan Leffler

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

Deduplicator
Deduplicator

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:

  1. 10000 bytes might be too much (just about always on the stack, which is often severely limited. Consider heap-allocation with malloc(), or static buffers).
  2. The input might contain a token more that 9999 bytes long (+1 for terminator).
  3. You do not check for input-failure, but will probably blithely assume success.

Upvotes: 4

Related Questions