gpt4 book ai didi

c - 指向数组的指针数组

转载 作者:太空狗 更新时间:2023-10-29 17:06:22 24 4
gpt4 key购买 nike

我是 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;
}

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

最佳答案

您的术语有些乱七八糟。我认为回答您问题的最简单方法是逐行检查您的代码。

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],这更常见。

关于c - 指向数组的指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11363226/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com