-2

I am trying to find out what this casting operation do:

char w[12] = {0};
int r;

r = (int)gets(w);

When input is for example 156, the value of r is -1073744588, so it is not a simple conversion to integer.

user187205
  • 330
  • 1
  • 2
  • 16
  • 3
    Do not use `gets`, first of all. – lost_in_the_source Mar 18 '17 at 14:34
  • 3
    Possible duplicate of [Converting string to integer C](http://stackoverflow.com/questions/7021725/converting-string-to-integer-c) – Andrew Henle Mar 18 '17 at 14:37
  • 2
    You're not casting a string, you're casting a pointer. See, eg: http://stackoverflow.com/questions/4872923/conversion-of-integer-pointer-to-integer or better would be to consult a C reference. – Paul Hankin Mar 18 '17 at 14:37
  • 2
    In fact, it is "a simple conversion". `gets` returns a memory address (which is a number), and that address is simply converted to an `int` (possibly giving a negative result, because in general this simple conversion doesn't make much sense). – hyde Mar 18 '17 at 14:42
  • 1
    Not sure why you ask about a code that makes no sense. Wherever you've found this, leave that place alone... – Karoly Horvath Mar 18 '17 at 14:44

1 Answers1

1

What your code does is cast the return value of gets, which is a pointer to the first character of the user input string, into an int. In other words, you are putting the address of the string into an integer, r. However, the address is so high that it "wraps around" in the integer r, yielding the large negative value.

You are most likely trying to convert the user's input into an int. This is the code to do so

char buf[80];
int res;

if (fgets(buf, sizeof buf, stdin))      /* load input into buf */
    if (sscanf(buf, "%d\n", &res) < 1)  /* try to read integer from buf */
        fprintf(stderr, "Bad input\n"); /* input was bad; write error */

Notice, you should never use gets because it has serious security problems. Use fgets instead to read a line from the standard input.

lost_in_the_source
  • 10,998
  • 9
  • 46
  • 75