c - 在 C 中使用指针打印数组的值

标签 c multidimensional-array

非常基本的问题。诀窍在于该数组被定义为二维数组。

int main(){
    int mat[3][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    int index;
    for (index = 0; index < 9; index++){
        // only change code below this line
        // print the value at this index using pointer arithmetic

        //below is my code
        printf("%p\n", *(&mat + index));
    }
    return 0;
}

我是指针新手。据我了解,“&”指针指向地址,*指针指向该地址中的值,对吗?

输出应该是单独一行上的整数 1-9

最佳答案

您的意思似乎是以下

#include <stdio.h>

#define N   3

int main(void) 
{
    int mat[N][N] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

    for ( int i = 0; i < N * N; i++ )
    {
        printf( "%d ",  *( *( mat + i / N ) + i % N ) );
        if ( ( i + 1 ) % N == 0 ) printf( "\n" );
    }

    return 0;
}

输出为

1 2 3 
4 5 6 
7 8 9 

另一种方法是将二维数组重新解释为一维数组。

#include <stdio.h>

#define N   3

int main(void) 
{
    int mat[N][N] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

    for ( int i = 0; i < N * N; i++ )
    {
        printf( "%d ",  *( ( int * )mat + i ) );
        if ( ( i + 1 ) % N == 0 ) printf( "\n" );
    }

    return 0;
}

如果您需要将所有整数输出在一行中,则只需删除 if 语句即可。

关于c - 在 C 中使用指针打印数组的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42262374/

相关文章:

c++ - 二维数组中的沙漏总和

java - 如何在java中按元素数量对2D字符串数组进行排序

java - 二维数组无法移动

javascript - 获取并检查数组的 javascript 数组

c - C 中奇怪的内存损坏

c - 使用 C 编程的 scanf() 后不显示输出

c - 如何通过检查分隔符在字符串中添加字符?

c++ - 将文件内容复制到多维数组中

c - ANSI C - 数字矩阵的输入

C 函数和 NaN