爲什麼下面的代碼編譯:如何聲明一個指針?
int main()
{
int j = 1;
int *jp = &j;
cout << "j is " << j << endl;
cout << "jp is " << jp << endl;
cout << "*jp is " << *jp << endl;
cout << "&j is " << &j << endl;
cout << "&jp is " << &jp << endl;
}
,但不爲呢?
#include <iostream>
using namespace std;
int main()
{
int j = 1;
int *jp;
*jp =& j; // This is the only change I have made.
cout << "j is " << j << endl;
cout << "jp is " << jp << endl;
cout << "*jp is " << *jp << endl;
cout << "&j is " << &j << endl;
cout << "&jp is " << &jp << endl;
}
這個編譯當我做jp = &j
,爲什麼?我只在另一行初始化了jp
,這對我沒有意義。
你在編譯時會得到什麼錯誤? –
prog.cpp:9:錯誤:從'int *'無效轉換爲'int'結果:編譯錯誤 – user1084113
感謝您的快速回復傢伙,你的答案真的幫了大忙。 – user1084113