【问题标题】:variable is losing its value in c program变量在c程序中失去了它的价值
【发布时间】:2017-07-04 23:08:01
【问题描述】:

这是用 'c' 编写并用 gcc 编译的。我不确定您还需要知道什么。

我可以放在一起的最小的完整示例如下所示。变量 'numatoms' 在到达第 23 行时(在 scanf() 之后)丢失了它的值。

我被难住了。也许它与 scanf() 覆盖 numatoms 的空间有关?

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

/*
 * 
 */
int main(int argc, char** argv) {
uint8_t numatoms;
uint8_t r;
char a[20];

do {
    printf("NO. OF ATOMS?");
    fflush(stdout);
    scanf("%d", &numatoms);
    printf("\r\n");
    for(;;){
        printf("value of numatoms is %u\r\n", numatoms);
        printf("RAY?");
        fflush(stdout);
        scanf("%u", &r);
        printf("value of numatoms is %u\r\n", numatoms);
        if(r < 1)
            break;
        else {
            printf("value of numatoms is %u\r\n", numatoms);
        }
    }
    printf("CARE TO TRY AGAIN?");
    fflush(stdout);
    scanf("%s", a); 
    printf("\r\n");           
} while (a[0] == 'y' || a[0] == 'Y');

return (EXIT_SUCCESS);

}

【问题讨论】:

  • @PatrickRoberts 不是吗?
  • 没关系,显然我错了。
  • scanf("%d", &amp;numatoms); --> scanf("%" SCNu8, &amp;numatoms); (&lt;inttypes.h&gt;)
  • 为了便于阅读和理解:1) 一致地缩进代码。在每个左大括号“{”后缩进。在每个右大括号 '}' 之前不缩进。建议每个缩进级别 4 个空格。 2) 通过一个空行分隔代码块(for、if、else、while、do...while、switch、case、default)。
  • 向用户输出提示时,不需要刷新标准输出。调用输入函数scanf() 的行为将导致显示提示。

标签: c integer scanf


【解决方案1】:

uint8_t 是 8 位长 %u 读取一个无符号整数(可能是 32 位长)。

您要么需要使numatoms“更大”(即unsigned int),要么读取正确的大小(参见scanf can't scan into inttypes (uint8_t)

【讨论】:

    【解决方案2】:

    您应该使用宏作为在标题&lt;inttypes.h&gt; 中定义的整数类型的格式说明符。

    来自 C 标准(格式说明符的 7.8.1 宏)

    1 以下每个类似对象的宏都扩展为一个字符 包含转换说明符的字符串文字,可能由 长度修饰符,适合在 a 的格式参数中使用 转换相应格式时的格式化输入/输出函数 整数类型。这些宏名称具有 PRI 的一般形式 (fprintf 和 fwprintf 系列的字符串文字)或 SCN (fscanf 和 fwscanf 系列的字符串文字),217) 后跟转换说明符,后跟对应的名称 到 7.20.1 中的类似类型名称。在这些名称中,N 代表 7.20.1 中描述的类型的宽度。

    用于带有转换说明符u 的无符号整数类型的宏的一般形式如下所示

    SCNuN
    

    这是一个演示程序

    #include <stdio.h>
    #include <stdint.h>
    #include <inttypes.h>
    
    int main(void) 
    {
        uint8_t x;
    
        scanf( "%" SCNu8, &x );
    
        printf( "x = %u\n", x );
    
        return 0;
    }
    

    【讨论】:

    • 我喜欢这个网站。所以要清楚,这真的是 scanf("%u", &r); “覆盖”“numatoms”位置的行确实使 scanf 无法限制为一个字节。 'numatoms' 被它的 scanf() 正确设置(虽然也应该被修复),这是第二个 scanf() 搞砸了。
    • @user1160866 两个scanf调用的问题是一样的。结果,变量周围的内存被覆盖了。
    猜你喜欢
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-17
    • 1970-01-01
    • 2013-03-07
    • 1970-01-01
    相关资源
    最近更新 更多