Re: [問題] 簡單指標釐清

看板C_and_CPP (C/C++)作者 (大餅welcome back)時間15年前 (2010/10/10 17:09), 編輯推噓3(308)
留言11則, 3人參與, 最新討論串2/3 (看更多)
※ 引述《mgupo (mgupo)》之銘言: : 遇到的問題: 最近主要在研究指標的用法,尤其是在function間傳遞的問題 : 希望得到的正確結果: Compiler不要有Warning : 程式跑出來的錯誤結果: [Warning] passing arg 1 of `test' from incompatible : pointer type : 開發平台: Dev-C++ : 有問題的code: 我的程式主要分成main以及test : int main(){ : int *a = 3; : test(&a); : } : void test(int *b){ : printf("%d",*b); : } : 補充說明: 其實上面的CODE是可以執行的,結果也對,但是會跑那個Warning讓我不解, : 因為就我的認知,型態似乎是正確的,不知道是不是有觀念錯了呢?? 結果當然是不對 int *a = 3代表你把a設成3 也就是對電腦來說變數a的rvalue是位址0x3,指向一個int 當然是錯的 0x3根本沒東西...你指向一個未初始化的記憶體區塊... 然後你取a的位址 所以傳進test的是a的lvalue 型態是int** 被compiler implicitly cast之後變成int* 取值之後傳進printf 所以也就是你對a的lvalue做一次取值抓出a的rvalue 也就是你一開始設的"未初始化的記憶體位址0x3" 你又告訴printf這是一個signed int 自然會印出看起來像是對但是其實從頭錯到尾的3... -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 68.122.89.18

10/10 17:11, , 1F
?!這就是我想要問的~所以int *a=3,其實a代表的還是記憶體位
10/10 17:11, 1F

10/10 17:11, , 2F
址嗎??
10/10 17:11, 2F
As what you told your compiler, a is an "int pointer."

10/10 17:15, , 3F
a所指的位址,該位址指到的值是3
10/10 17:15, 3F

10/10 17:15, , 4F
上面說位址是0x3,感覺怪怪的
10/10 17:15, 4F
Nothing weird at all. The line "int* a = 3" is equivalent to the following two lines "int* a; a = 3;" That is to say, you are setting your pointer to the address 0x3. If you use g++, it will tell you that's an invalid conversion from "int" to "int*". And that's what it means.

10/10 17:15, , 5F
可是如果這樣的話~我printf("%X",a)的時候,應該要得到位址
10/10 17:15, 5F

10/10 17:16, , 6F
但實際上我得到的就是3耶~
10/10 17:16, 6F
First of all, you should use %p to print a pointer. Second, yes, you're printing a, which is a "pointer" and it has been set to 3. It does not mean you set the integer to 3; rather, you set the "pointer" to 3. It seems to be correct is simply because you're using int. Try other incompatible data type like double or string, your compiler will not allow you to do that any more. ※ 編輯: proLIONS 來自: 68.122.89.18 (10/10 17:31) You may also simply try "printf("%d\n", *a);" which will give you a sig11, since address 0x3 is not present in your memory allocation. ※ 編輯: proLIONS 來自: 68.122.89.18 (10/10 17:33)

10/10 17:44, , 7F
其實他沒有對 a 作 dereference的動作, 這時用法實際
10/10 17:44, 7F

10/10 17:44, , 8F
上跟 if( a != 0 ) 有異曲同工之妙, 皆是可以做為一個
10/10 17:44, 8F

10/10 17:45, , 9F
測試的條件, 只要不對他做提取即可, 只是這麼一來就要
10/10 17:45, 9F

10/10 17:46, , 10F
很小心他的用法, 甚至連 int *a = 3; 這裡有一個隱式
10/10 17:46, 10F

10/10 17:46, , 11F
轉換都要知道, 才會知道這樣做為什麼危險
10/10 17:46, 11F
文章代碼(AID): #1CiOAzQ8 (C_and_CPP)
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 3 篇):
文章代碼(AID): #1CiOAzQ8 (C_and_CPP)