我不知道如何将指针传递到这个 for 循环中,所以我不会获得随机内存值。在 printf 中使用指针在 for 循环之外可以正常工作,但在内部则不行。
查看后,我不确定是否使用 * 或 & 运算符传递我的变量。
#include <stdio.h>
int main()
{
int mat1[3][3]={{1,2,3},{4,5,6},{7,8,9}};
int mat2[3][3]={{1,2,3},{4,5,6},{7,8,9}};
int *mat1pnt=&mat1[0][0];
printf("%d\n",*(mat1pnt));//works fine without for loop
int i=0;
int j=0;
for(i==0;i<=2&&j<=2;j++,&mat1pnt)
{
printf("%d",&mat1pnt);
}
//int *mat1pnt=&mat
return 0;
}
最佳答案
您不能像使用函数那样将值传递给 for
循环(并非所有带大括号的都表示函数)。 for
循环是一个代码块,除了定义自己的变量之外,还可以访问嵌入该 block 的位置定义的变量。
似乎您想使用指针迭代二维数组。要访问值,您需要取消引用指针(即运算符 *
)。要让指针移动到下一个元素,请将其递增(运算符++
)。并且您需要迭代 #columns x #rows
项,即您的情况下的 3*3
:
for(int i=0; i<3*3; i++)
{
printf("%d",*mat1pnt); // dereference, i.e. get the value
mat1pnt++; // move pointer to the next value
}
关于c - 在 for 循环中使用指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56727756/