指向数组的指针数组
我是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 (ie 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
列的值。 这称为指针算术(这里有关于指针算术的附加信息)
大多数人发现语法*(tab[j] + i)
是笨重的,但它更能描述实际发生的事情。 在C中,您可以将其重写为tab[j][i]
,这更常见。
您已按预期存储数据,只需正确访问即可
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[]
数组的地址
编辑:在回应Jerome的评论时,您可以通过声明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};
然后基本上以矩阵的forms, tttt
是tab
的转置
你存储了一切,但你没有显示它。 尝试
for (i=0; i<4;i++) { for (j=0; j<4; j++) printf("%d\t", *(tab[i]+j)); }