開發平台(Platform): (Ex: Win10, Linux, ...)
win7
編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出)
Dev C++
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
問題(Question):
[Error] cannot convert 'int (*)[size]' to 'int*' in assignment
餵入的資料(Input):
預期的正確結果(Expected Output):
錯誤結果(Wrong Output):
[Error] cannot convert 'int (*)[size]' to 'int*' in assignment
程式碼(Code):(請善用置底文網頁, 記得排版,禁止使用圖檔)
int main()
{
int i,a[5] = {32,16,9,7,0};
cout<<"a = "<<a<<endl;
cout<<"&a = "<<&a<<endl;
cout<<"&a[0] = "<<&a[0]<<endl;
int sum = 0;
sum = 0;
int *ptr;
ptr = &a; // why this is not acceptable
// ptr = &a[0];
// ptr = a;
for(i = 0;i<5;i++)
{
sum += *ptr;
ptr += 1;
}
return 0;
}
補充說明(Supplement):
ptr = &a; // why this is not acceptable
// ptr = &a[0];
// ptr = a;
只有第一行給出錯誤訊息,後兩行都可以,但我不明白為什麼,
從上面print out 的結果看起來
a == &a == &a[0]
如果是單個變數 int *ptr= &a; 給過
不明白為什麼陣列a不能。
謝謝解說 感恩
作者:
OnlyRD (里巷人)
2022-05-21 16:32:00怎麼會是&a?a = int [5] , &a 當然變成 pointer to array of int , 隱式轉型成int** . 去把 right-left rule 看一遍,就全部搞懂了。如果要更進一步計較int** or int[5]* ,會在template裡面考慮,有可能需要decay出場,否則在指標操作上,考慮隱式轉換就好了。