您的術語轉置是有點所有的地方。我認爲最簡單的方法來回答你的問題是逐行瀏覽你的代碼。
int main()
{
int t1[4]={0,1,2,3}; //Declares a 4 integer array "0,1,2,3"
int t2[4]={4,5,6,7}; //Declares a 4 integer array "4,5,6,7"
int t3[4]={8,9,10,11}; //Declares a 4 integer array "8,9,10,11"
int t4[4]={12,13,14,15}; //Declares a 4 integer array "12,13,14,15"
int *tab[4]={t1,t2,t3,t4};//Declares a 4 pointer of integers array "address of the first element of t1, address of the first element of t2, ..."
int i,j,k,l; //Declares 4 integer variables: i,j,k,l
for (i=0; i<4;i++)
{
printf("%d\t", *tab[i]); //print out the integer that is pointed to by the i-th pointer in the tab array (i.e. t1[0], t2[0], t3[0], t4[0])
}
return 0;
}
你所做的一切似乎都可以,直到你的循環。你只顯示每個數組的第一個整數,因爲你沒有經過它們。遍歷它們,你的代碼應該是這樣的:
for (i=0; i<4;i++)
{
for (j=0; j<4; j++)
{
printf("%d\t", *(tab[j] + i));
}
}
上面的代碼使用了兩個循環計數器,數組中的一個(在i
)要經過數組中的位置(第一個值,在第二個值陣列等);另一個通過不同的陣列(j
)。它通過檢索存儲在tab[j]
中的指針並創建一個具有右偏移量的新指針來顯示i
列的值。這被稱爲指針運算(有關於指針運算here附加信息)
大多數人覺得語法*(tab[j] + i)
是笨重,但它更描述了什麼是真正發生。在C中,您可以將其重寫爲tab[j][i]
,這更常見。
'* tab [i]'與tab [i] [0]'相同。 'tab [i] [1]','tab [i] [2]',...會發生什麼?...? – pmg 2012-07-06 13:38:52
那:'for(i = 0; i <4; ++ i){printf(「%d%d%d%d \ n」,tab [0] [i],tab [1] [i],標籤[2] [i],標籤[3] [i]);}'? – fork0 2012-07-06 13:39:42