简体   繁体   English

相同的声明以不同的顺序在gcc中产生不同的结果

[英]The same declaration in a different order produce different results in gcc

The problem is in line 7: int ret=3, x, y; 问题在第7行: int ret=3, x, y;

if I declare the y first (like the line 8) the result will be different 如果我先声明y(如第8行),结果将有所不同

on my computer right now is printing only the Y values​​, with this change in the declaration goes to print only the values ​​of X 现在我的计算机上仅打印Y值,声明中的此更改仅打印X的值

Makefile Makefile文件

gcc -g -o open_file_test open_file_test.c;
./pen_file_test input

CODE: 码:

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

int worldsize = 0;

int main(int argc, char const *argv[]){
    int ret=3, x, y;
    //int ret=3, y, x;
    char chr;
    int teste;

    FILE * inputFile;
    inputFile = fopen(argv[1],"r");
    teste = fscanf(inputFile,"%d", &worldsize);
    printf("Tamanho: %d\n", worldsize);

    while(1){
        ret=fscanf(inputFile,"%d %d %s\n", &x, &y, &chr);
        if(ret != 3)
            break;
        printf("x: %d  y: %d\n", x, y);
    }
    printf("End File :D\n");
    return 0;
}

input_file 输入文件

 10 1 0 w 2 1 s 6 9 w 3 7 w 5 0 s 1 5 t 1 5 t 7 5 t 9 7 t 9 3 t 0 0 i 

output 产量

 Tamanho: 10 x: 0 y: 0 x: 0 y: 1 x: 0 y: 9 x: 0 y: 7 x: 0 y: 0 x: 0 y: 5 x: 0 y: 5 x: 0 y: 5 x: 0 y: 7 x: 0 y: 3 x: 0 y: 0 End File :D 

On my computer only read the Y, and the same code on my colleague computer only reads X, and in another friend's computer works fine (read the X and Y), can somebody explain the reason? 在我的计算机上仅读取Y,而在同事计算机上的相同代码仅读取X,而在另一位朋友的计算机上工作正常(读取X和Y),有人可以解释原因吗?

You have undefined behaviour in your code here: 您的代码中有未定义的行为:

fscanf(inputFile,"%d %d %s\n", &x, &y, &chr);

Reading a string into chr which is a single char variable. 将字符串读取到chr ,这是一个char变量。 Even if the string contains a single character, a null-terminator will be written after it. 即使字符串包含单个字符,也将在其后写入一个空终止符。 This may well be spilling into your integers on the stack. 这很可能会溢出到堆栈中的整数中。

If you want a single char, then use %c : 如果要一个字符,请使用%c

fscanf(inputFile,"%d %d %c\n", &x, &y, &chr);

If you prefer a string, then make chr a char array large enough to hold any potential string (plus a null terminator). 如果您喜欢使用字符串,则将chr设为足够大的char数组,以容纳任何可能的字符串(加上空终止符)。 Alternatively, use fgets to read a line at a time and then parse the values out later. 或者,使用fgets读取一行,然后稍后解析这些值。

On this line: 在这行上:

ret=fscanf(inputFile,"%d %d %s\n", &x, &y, &chr);

Your fscanf format has %s , which means "String" (several characters, ending with a NULL-terminator) , but the matching variable for the data, chr is only a single character, and cannot handle multiple characters. 您的fscanf格式具有%s ,表示“ String” (几个字符,以NULL终止符结尾) ,但是数据的匹配变量chr只是单个字符,不能处理多个字符。

To fix it, I recommend using formatter %c (which means a single character) instead of %s . 要解决此问题,我建议使用格式化程序%c (表示单个字符),而不要使用%s

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

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