c - 在 for 循环中使用指针

标签 c

我不知道如何将指针传递到这个 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/

相关文章:

c - 这两种说法有什么区别?

c - 兄弟子进程之间的管道份额

c - 使用埃拉托斯特尼筛法的质因数

c - 在 C 中,结构数组如何在内存中查找

c - 给定一个基于另一个的限制指针,它们应该永远不要别名吗?

c - 释放它们后真的应该将指针设置为 `NULL` 吗?

c - 是否可以在 GTK 中对用户隐藏 .glade 文件?

c - Linux 在崩溃时自动重启应用程序 - 守护进程

c - Linux C++ : test of the cacheline size performance effect not as expected

C++/C : Prepend length to Char[] in bytes (binary/hex)