Re: [問題] 簡單指標釐清
看板C_and_CPP (C/C++)作者proLIONS (大餅welcome back)時間15年前 (2010/10/10 17:09)推噓3(3推 0噓 8→)留言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
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
10/10 17:15, 3F
→
10/10 17:15, , 4F
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
10/10 17:15, 5F
→
10/10 17:16, , 6F
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
10/10 17:44, 7F
→
10/10 17:44, , 8F
10/10 17:44, 8F
→
10/10 17:45, , 9F
10/10 17:45, 9F
→
10/10 17:46, , 10F
10/10 17:46, 10F
→
10/10 17:46, , 11F
10/10 17:46, 11F
討論串 (同標題文章)
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章