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.
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.
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.