2012-07-06 85 views
4

我新的C編程,這是我的問題:陣列指針到陣列

欲每個陣列的第一值存儲在一個新的數組,在一個新的陣列中的每個陣列的隨後的第二個值等等。

我可以聲明指針數組,但我不知道如何使用它!

請幫我。

int main() 
{ 
    int t1[4]={0,1,2,3}; 
    int t2[4]={4,5,6,7}; 
    int t3[4]={8,9,10,11}; 
    int t4[4]={12,13,14,15}; 
    int *tab[4]={t1,t2,t3,t4}; 
    int i,j,k,l; 
    for (i=0; i<4;i++) 
    { 
     printf("%d\t", *tab[i]); 
    } 

    return 0; 
} 

當我這樣做時,我只存儲每個數組的第一個值。

+1

'* tab [i]'與tab [i] [0]'相同。 'tab [i] [1]','tab [i] [2]',...會發生什麼?...? – pmg 2012-07-06 13:38:52

+0

那:'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

回答

1

你存儲的一切,但你只是不顯示它。嘗試

for (i=0; i<4;i++) 
{ 
    for (j=0; j<4; j++) 
    printf("%d\t", *(tab[i]+j)); 
} 
+2

ITYM'printf(「%d \ t」,tab [i] [j]);'或'printf(「%d \ t」,*(tab [i] + j));' – pmg 2012-07-06 13:43:18

+0

問題要求打印每個數組的第一個元素,然後是第二個,然後是第三個。 *不是*第一個數組,然後第二個數組等。 – Jerome 2012-07-06 14:02:35

3

你存儲你想要的數據,你只需要訪問它正確

for (i=0; i<4;i++) 
{ 
    for (j = 0; j < 4; j++) { 
    int* temp = tab[i];  
    printf("%d\t", temp[j]);  // or try the next line... 
    printf("%d\t", *(temp + j)); // prints same value as above line 
    printf("%d\t", tab[i][j];  // the same value printed again 
    } 
} 

上述所有打印相同的值,它只是不同的使用訪問該值的方法指針算術。的tab每個元素都是一個int*各自的價值是你的其他的地址定義int[]陣列在開始

編輯:針對傑羅姆的評論,你可以做到這一點通過聲明4個陣列

int tab1[4]={*t1,*t2,*t3,*t4}; 
int tab2[4]={*(t1+1),*(t2+1),*(t3+1),*(t4+1)}; 
int tab3[4]={*(t1+2),*(t2+2),*(t3+2),*(t4+2)}; 
int tab4[4]={*(t1+3),*(t2+3),*(t3+3),*(t4+3)}; 

現在tab1包含每個數組的第一個元素,tab2第二個元素,依此類推。 然後你可以使用

int *tttt[4]={tab1,tab2,tab3,tab4}; 
for (i=0; i<4;i++) { 
    for (j = 0; j < 4; j++) { 
    printf("%d\t", tttt[i][j]); 
    } 
} 

打印你想要的東西。如果你聲明的另一個指針數組像你這樣在開始

int* tab[4] = {t1,t2,t3,t4}; 

則基本上在矩陣方面,tttttab

+0

問題要求打印每個數組的第一個元素,然後是第二個,然後是第三個。 *不是*第一個數組,然後是第二個數組等。 – Jerome 2012-07-06 14:02:28

11

您的術語轉置是有點所有的地方。我認爲最簡單的方法來回答你的問題是逐行瀏覽你的代碼。

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],這更常見。