作者NoStra ()
看板C_and_CPP
標題[問題] c 陣列與指標
時間Wed Feb 3 21:53:54 2016
I have met some questions about pointer in C.
int main()
{
int a[5][2] = {0,1,2,3,4,5,6,7,8,9};
int *p = a[0];
int (*p2)[2] = &a[1];
++p;
++p2;
// 1, a[0][1]
printf("%d\n",*p);
// 4, a[2][0]
printf("%d\n",**p2);
// 9, but I think it would run out of index. (2 > 1) -> error
printf("%d \n",p2[1][2]);
return 0;
}
Could anyone give me some comments about it.
BTW, How to get 5 using pointer p2?
Can *(*p2+1) get 5 ?
Thanks.
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.229.141.7
※ 文章網址: https://webptt.com/m.aspx?n=bbs/C_and_CPP/M.1454507637.A.887.html
※ 編輯: NoStra (36.229.141.7), 02/03/2016 21:56:44
1F:→ stupid0319: int (*p2)[2] = &a[1]; 我看不懂這一行在做什麼T.T 02/03 22:06
2F:→ arthur104: just treat p2[1][2] as *(*p2 + 2 * 1 + 2) 02/03 23:50
3F:→ arthur104: *(*p2 + 1) = 5 is correct. 02/03 23:51
4F:推 qscgy4: 理解就好,別用這種寫法搞自己搞別人,就用p[r][c]來存取 02/04 13:37
5F:推 CoNsTaR: *p2 is an array of int *(*p2 + 3) = 5 02/04 16:03
6F:→ Frozenmouse: it's your job to check the index bounds 02/04 16:59
7F:→ Frozenmouse: this is not Java lol 02/04 17:00