【问题标题】:When and How the pointer arithmetic evaluate?指针算术何时以及如何评估?
【发布时间】:2020-09-26 05:45:38
【问题描述】:

我总是认为指针算术是理所当然的。但有时它会困扰我,编译器究竟做了什么,它们什么时候被评估?考虑下面的程序:

#include <stdio.h>
#include <stdlib.h>

int prng(void);

int main()
{
    int x = prng(); // Pseudo Random Generator.

    int (*a)[x];

    a = malloc(sizeof(int) * 2 * x);    // Allocate 2 rows of x columned vectors

    printf("%p %p\n", a, a + 1);    // How and When does a + 1 evaluate ?

    return 0;
}

我几乎可以肯定编译器(或运行时的程序)不会要求 CPU 像普通整数一样添加 a1 来评估 a+1。那么编译器(或程序)如何获取正确的地址呢?

【问题讨论】:

  • ptr + n 将 n steps 添加到 ptr。每个 step 的大小为 sizeof *ptr。在您的示例中,a + 1 增加了 1 个 step 的大小 sizeof *a == sizeof (int[x]) == x * sizeof (int)
  • x 是VLA 时,它在运行时以及sizeof(x) 进行评估
  • @pmg 编译器是否用x * sizeof (int) 替换a+1 中的1
  • 不知道编译器是怎么做的。
  • @MohithReddy 如果你真的想知道编译器是怎么做的,看看生成的汇编输出,但你不应该关心。

标签: c pointers variable-length-array


【解决方案1】:

那么编译器(或程序)如何设法获得正确的地址?

a + 1 在运行时进行评估。

在运行时,*a 的大小为x * sizeof(int)

总和是通过将axints 添加到它而形成的。


注意:

int (*a)[x];x &lt;= 0 时是 UB。

a + 1是分配失败时的UB。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-18
    • 2023-03-11
    • 2016-06-05
    • 2019-10-04
    • 2019-03-31
    • 2016-05-10
    • 2021-05-02
    • 1970-01-01
    相关资源
    最近更新 更多