簡體   English   中英

相同的聲明以不同的順序在gcc中產生不同的結果

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

問題在第7行: int ret=3, x, y;

如果我先聲明y(如第8行),結果將有所不同

現在我的計算機上僅打印Y值,聲明中的此更改僅打印X的值

Makefile文件

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

碼:

#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;
}

輸入文件

 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 

產量

 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 

在我的計算機上僅讀取Y,而在同事計算機上的相同代碼僅讀取X,而在另一位朋友的計算機上工作正常(讀取X和Y),有人可以解釋原因嗎?

您的代碼中有未定義的行為:

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

將字符串讀取到chr ,這是一個char變量。 即使字符串包含單個字符,也將在其后寫入一個空終止符。 這很可能會溢出到堆棧中的整數中。

如果要一個字符,請使用%c

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

如果您喜歡使用字符串,則將chr設為足夠大的char數組,以容納任何可能的字符串(加上空終止符)。 或者,使用fgets讀取一行,然后稍后解析這些值。

在這行上:

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

您的fscanf格式具有%s ,表示“ String” (幾個字符,以NULL終止符結尾) ,但是數據的匹配變量chr只是單個字符,不能處理多個字符。

要解決此問題,我建議使用格式化程序%c (表示單個字符),而不要使用%s

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM