看板 C_and_CPP 關於我們 聯絡資訊
#include <stdio.h> #include <stdlib.h> #include <iostream.h> #include <conio.h> void main(void) { FILE *fp_2; int i,j,bit,num,out=0,match; char file_name_2[20]=""; char h_1[5]; printf("file name_2:");//霍夫曼表 scanf("%s",file_name_2); if((fp_2=fopen(file_name_2,"r"))==NULL) { printf("test file name error!!\n"); exit(1); } fscanf(fp_2,"%s",&h_1); cout<<h_1; fclose(fp_2); } 我故意只將陣列大小給5,但是掃入11001111111110,為何我在輸出時還是可以完整輸出 照理說大小只有5只能存11001不是嗎? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.42.200.81
sosokill:Char是8byte? 05/11 22:57
i1537:一維陣列 不是 存取的長度 05/11 23:02
sosokill:fscanf這個函數去查看看 我沒用過 感覺是這裡造成的 05/11 23:10
VictorTom:雖然你只宣告char [5], 但是考慮記憶體對齊等情況, 有時 05/11 23:22
VictorTom:後的確會有這種超用了沒出事的case, 但基本上這樣的程式 05/11 23:23
VictorTom:都是unstable的, 尤其也許debug版OK, release馬上掛給你 05/11 23:23
VictorTom:看, 或反過來; 最主要的原因是, 你區域變數範圍超用, 就 05/11 23:23
VictorTom:會複寫到stack裡的data, 到時候程式關閉時發生錯誤或者 05/11 23:24
VictorTom:call function回不去你就知道了:) 另外, 這種情況下執行 05/11 23:25
VictorTom:到該行會印出全部, 是因為char string是以\0當作結束的 05/11 23:26
VictorTom:條件, 所以印那麼長的理由不在[]大小, 而在'\0'的位置. 05/11 23:27
VictorTom:當然你要是寫/讀的更長踩到了當場就會爛的地方就先當了. 05/11 23:27