简体   繁体   English

为什么变量声明的位置很重要?

[英]Why placement of declaration of variable is important?

The main task for my code is to take out data from outside files and then ascribe a number at the beginning.我的代码的主要任务是从外部文件中取出数据,然后在开头指定一个数字。 The problem is that the code below works just fine.问题是下面的代码工作得很好。

#include <stdio.h>

int main(void) {
    char name[20], surname[30], group[2];
    puts("Now i download data from file");
    int n = 1, number;
    while (!feof(stdin)) {
        scanf ("%s %s %d %s", name, surname, &number, group);
        printf("%d. %s | %s | %d | %s", n, name, surname, number, group);
    }
    return 0;
}

But when I change the position of one line it sets the value of n to 0 and doesn't rise.但是当我改变一行的位置时,它会将n的值设置为 0 并且不会上升。

#include <stdio.h>

int main(void) {
    int n = 1, number;
    char name[20], surname[30], group[2];
    puts("Now I download data from file");
    while (!feof(stdin)) {
        scanf ("%s %s %d %s", name, surname, &number, group);
        printf("%d. %s | %s | %d | %s", n, name, surname, number, group);
    }
    return 0;
}

Your code has potential undefined behavior: if the data file contains fields that exceed the maximum length storable in the destination arrays, fscanf() will cause a buffer overrun and overwrite something else in memory, possibly another local variable.... Changing the order of the local variable definitions may change the side effects of this bug.您的代码具有潜在的未定义行为:如果数据文件包含超过目标数组中可存储的最大长度的字段, fscanf()将导致缓冲区溢出并覆盖内存中的其他内容,可能是另一个局部变量......更改顺序局部变量定义可能会改变这个错误的副作用。 Undefined behavior can lead to anything, from no visible effect to the program crash or even a market crash.未定义的行为可能导致任何事情,从没有明显影响到程序崩溃甚至市场崩溃。

Also note that while (!feof(stdin)) is always wrong .还要注意while (!feof(stdin))总是错误的

Here is how you can modify your code to avoid this undefined behavior and verify that the data file is correctly converted:以下是您可以修改代码以避免这种未定义行为并验证数据文件是否正确转换的方法:

#include <stdio.h>

int main(void) {
    char buf[128];
    char name[20], surname[30], group[2];
    int n = 1, number;
    char dummy;

    puts("Now I download data from file");

    while (fgets(buf, sizeof buf, stdin)) {
        if (sscanf("%19s %29s %d %1s %c", name, surname, &number, group, &dummy) == 4) {
            printf("%d. %s | %s | %d | %s\n", n++, name, surname, number, group);
        } else {
            printf("Invalid format: %s", buf);
        }
    }
    printf("%d records\n", n);
    return 0;
}

Any records with a group larger than a single character will cause a format error. group大于单个字符的任何记录都会导致格式错误。 If the group may have 2 characters, you should define the array as char group[3] and convert it with %2s .如果该group可能有 2 个字符,则应将数组定义为char group[3]并将其转换为%2s The same remark applies to all string fields.同样的评论适用于所有字符串字段。

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

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