[問題] cannot convert int (*)[size] to int*

看板C_and_CPP (C/C++)作者 (不要改我暱稱)時間1年前 (2022/05/17 15:33), 編輯推噓3(3010)
留言13則, 5人參與, 1年前最新討論串1/1
開發平台(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不能。 謝謝解說 感恩 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 98.149.118.248 (美國) ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1652772812.A.76D.html

05/17 15:41, 1年前 , 1F
&a 是 int** 吧?
05/17 15:41, 1F

05/17 16:19, 1年前 , 2F
如果開的變數是陣列a[5] a跟&a[0]是pointer &a則是
05/17 16:19, 2F

05/17 16:19, 1年前 , 3F
double pointer
05/17 16:19, 3F

05/17 16:22, 1年前 , 4F
因為&a是指向一個陣列的pointer,跟int*
05/17 16:22, 4F

05/17 16:23, 1年前 , 5F
一個指向int的pointer 型態不相容,沒法自動轉換。
05/17 16:23, 5F

05/17 16:23, 1年前 , 6F
純粹兩個位址相同不代表可以直接assign
05/17 16:23, 6F

05/17 16:23, 1年前 , 7F
其實錯誤訊息很清楚了 就是型態無法轉換
05/17 16:23, 7F

05/17 16:27, 1年前 , 8F
另外樓上講的不太正確 &a 的型態是 int (*)[5]
05/17 16:27, 8F

05/17 16:27, 1年前 , 9F
指的是 a pointer (*) to an array [] of size 5
05/17 16:27, 9F

05/17 16:27, 1年前 , 10F
containing integers 並不是什麼
05/17 16:27, 10F

05/17 16:27, 1年前 , 11F
pointer to pointer (**)
05/17 16:27, 11F

05/17 16:39, 1年前 , 12F
謝謝大家解惑。跪
05/17 16:39, 12F

05/17 16:54, 1年前 , 13F
推薦個網站:cdecl.org
05/17 16:54, 13F
文章代碼(AID): #1YWq_CTj (C_and_CPP)
文章代碼(AID): #1YWq_CTj (C_and_CPP)