【发布时间】: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 像普通整数一样添加 a 和 1 来评估 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