c - 需要解释 - 3-D 数组、指针

标签 c arrays pointers

我发现了这个片段:

#include<stdio.h>
int main()
{
    int a[2][2][2] = { {10,2,3,4}, {5,6,7,8} };
    int *p,*q;
    p=&a[2][2][2];
    *q=***a;
    printf("%d----%d",*p,*q);
    return 0;
}

输出:垃圾值 ---- 1

这是解释:

p=&a[2][2][2] you declare only two 2D arrays, but you are trying to access
the third 2D(which you are not declared) it will print garbage values. *q=***a starting address of a is assigned integer pointer. Now q is pointing to starting address of a. If you print *q, it will print first element of 3D array.    

但是,我仍然无法理解。我希望以一种易于理解的方式提供相同的内容(并不是我在提示上述解释)。

请提供第 6 行和第 7 行的说明

最佳答案

您的代码存在几个问题:

#include<stdio.h>
int main()
{
    int a[2][2][2] = { {10,2,3,4}, {5,6,7,8} };

a 被声明为 3D 数组,但您使用 2D 数组对其进行初始化。

    int *p,*q;
    p=&a[2][2][2];

p 被初始化为无效的内存位置。由于 a 每个维度只有 2 个元素,因此唯一有效的下标是 01

    *q=***a;

q 尚未初始化以指向内存中的有效位置。将 q*q 进行引用是未定义的行为。

    printf("%d----%d",*p,*q);
    return 0;
}

关于c - 需要解释 - 3-D 数组、指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17736380/

相关文章:

php - 使用 foreach 写入数据库

C++ 将两个 int 数组连接成一个更大的数组

C memcpy 函数内 2D 数组到 3D 数组

c++ - 如何返回指向多维数组的指针?

c - C 中神秘的(我认为)缓冲区溢出

c - 在ncurses/C中模拟bash "snow fall"脚本

javascript - 在Javascript中将具有树结构的数组转换为对象

c - 访问其他大小的 32 位字数组

在 C 中将字符串转换为字符串数组

c - 在 C 中的单独函数中初始化指针