简体   繁体   English

Scanf_s读取错误的输入

[英]Scanf_s reading wrong input

For this code below (in C) 对于下面的代码(在C中)

    int small_a, small_b;
    printf("Please input two numbers\n");
    scanf_s("%d %d", &small_a, &small_b);
    printf("%d %d", &small_a, &small_b);
    int test_2nd = small_a - small_b;
    if (test_2nd < 0) {
        printf("a is smaller %d", &small_a);
    }
    else {
    printf("b is smaller %d", &small_b);

The values it prints when I write 4 and 2 is a huge six digit number (5504620 and 5504608 in this case) I don't understand where it goes wrong. 当我写4和2时,它输出的值是一个巨大的六位数(在这种情况下为5504620和5504608),我不知道它出了什么问题。 stdio.h has been included as a header. stdio.h已作为头文件包含在内。

The problem here is in the print statement. 这里的问题在打印语句中。 In the code 在代码中

 printf("%d %d", &small_a, &small_b);

you don't need ( want ) to take ( print ) the address. 您不需要( 想要 )取得( 打印 )地址。 Remove that & . 删除&

That said, this actually invokes undefined behavior . 也就是说,这实际上会调用未定义的行为 %d with printf() expects an argument of type int and you're essentially supplying an int * , causing the UB. 使用printf() %d需要一个int类型的参数,而您实际上是在提供int * ,从而导致UB。

FWIW, to print an address (pointer), you need to use %p format specifier and cast the argument to void * FWIW,要打印地址(指针),您需要使用%p格式说明符并将参数强制转换为void *

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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