看板 b96902HW 關於我們 聯絡資訊
#include<stdlib.h> #include<stdio.h> struct MyStruct { char str[5]; int i; }; int main() { MyStruct my; my.i=100; gets(my.str); printf("str:%s\n",my.str); printf("i:%d\n",my.i); printf("address of i:%p\n",&my.i); printf("address of str:%p\n",my.str); int j; for (j=0;j<10;j++) printf("j:%d str[j]:%d address of str[j]:%p\n",j,my.str[j],&my.str[j]); system("pause"); return 0; } 為什麼在以上的Code打入1234567890時,i的值是12345呢?? 理由如下: 如果我們執行程式,不難發現,i是排在str開頭位置後的第8個,記憶體如下: ---- str ->| | ---- | | ---- | | ---- | | ---- | | ---- | | ---- | | ---- | | ---- i --> | | ---- | | ---- 如果大家組語還沒忘的話,就知道這是為了讓讀變數更快的排法 因此,若我們打入1234567890,記憶體就會變成,1的ASCII code 為(0x31) ---- str ->|31| ---- |32| ---- |33| ---- |34| ---- |35| ---- |36| ---- |37| ---- |38| ---- i --> |39| ---- |30| ---- 又intel為little Indian,因此讀i出來值會是(0x3039) = 12345 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 123.192.28.251
ilway25:當時就在想明明是ascii 12345怎麼會印出數字12345... 03/28 19:07
jimmycool:所以盡量不要用gets,用fgets吧:p 03/28 19:34
electgpro:MyStruct 宣告的時候前面要加 struct 吧?不用嗎? 03/28 21:47
wolfdigit:int預設是32bits, 所以i應該是0x00003039 03/28 22:12
a127a127:C++不用 03/28 23:52
electgpro:話說為什麼i會在那裏阿? 03/29 00:59
wfuny:其實i底下應該還有一個結束字元'\0'值為0,和一個沒動過的0 03/29 10:34