简体   繁体   中英

What happens when using scanf(“%d”, &c) while c is a char?

the code is like this:

char c;  
scanf("%d", &c);  

inputting 3...

My guess is that when 3 is inputted, it is as type int ;
and then type-demoted to char and assigned to c ;

I print the value of c in specifier %d yielding 3, seems to be as expected;
but printing the value of c with specifier %c yields --a blank-- on the terminal;this is one question...(1);
to test more I furthermore declare a variable ch with type char and initialized it like this:

char ch = 1;  

and the test is like this:

(i&j)? printf("yes") : printf("no");  

and the result is "no"
I print out the value of i&j , and it is 0
but 1&3 should be 1 ? this is another question....(2);
my question is (1) and (2)

You're actually invoking undefined behavior doing that.

By using the format string %d , you're telling scanf to expect an int* as a parameter and you're passing it a pointer to a single character. Remember that scanf has no further type information on what you're passing it than what you're putting in the format string.

This will result in scanf attempting to write an int sized value to memory at an address that points to a char sized reservation, potentially (and for most architectures) writing out of bounds.

After invoking UB, all bets are off on your further calculations.

Suppose that scanf() were not a varargs-function, but a plain ordinary function taking a pointer-to-int as the 2nd argument:

int noscanf(char *format, int *ptr)
{
  *ptr = 42;
  return 1;
}

int main(void)
{
  char ch;
  int rc;

      // This should *at least* give a warning ...
  rc = noscanf("Haha!" , &ch); 

  return 0;
}

Now, scanf() is a varargs function. The only way for scanf() to determine the type of the (pointer) arguments is by inspecting the format string. And a %d means : the next argument is supposed to be a pointer to int. So scanf can happily write sizeof(int) bytes to *ptr.

I can't see a variable j there. So i&j will be 0. And yes, if i == 1 and j == 3 then i & j == 1 .

(i&j)? printf("yes") : printf("no");
statement gives the output yes,for i=1 and j=3.

And for (1) question ASCII 3 is for STX char which is not printable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM