指向数组的指针数组

use*_*835 7 c

我是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;
}
Run Code Online (Sandbox Code Playgroud)

当我这样做时,我只存储每个数组的第一个值.

Jer*_*ome 12

你的术语到处都是.我认为回答你问题的最简单方法是逐行检查你的代码.

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;
 }
Run Code Online (Sandbox Code Playgroud)

在你的循环之前,你正在做的一切似乎都没问题.您只显示每个数组的第一个整数,因为您没有通过它们.要迭代它们,您的代码应如下所示:

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

上面的代码使用两个循环计数器,一个(i遍历)数组中的位置(数组中的第一个值,数组中的第二个值等); 另一个要经过不同的数组(j).它通过检索存储在其中的指针tab[j]并创建一个具有正确偏移量的新指针来显示i第th列的值.这被称为指针运算(有关于指针运算的其他信息在这里)

大多数人发现语法*(tab[j] + i)很笨拙,但它更能描述实际发生的情况.在C中,您可以将其重写为tab[j][i],这更常见.


Gab*_*abi 1

你存储了一切,但你只是不展示它。尝试

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

  • ITYM `printf("%d\t", tab[i][j]);` 或 `printf("%d\t", *(tab[i]+j));` (2认同)