C:地址运算符(&)是产生一个指针(地址+类型)还是仅产生一个地址? [英] C: Does the address operator (&) produce a pointer (address + type) or just an address?
问题描述
我所读到的有关地址运算符&
的大多数内容都说,它只是用来获取地址的.我最近听到它对生成成熟指针的描述有所不同.
Most of what I've read about the address operator, &
, says it's used to get just that - an address. I recently heard it described differently, though, as producing a full-fledged pointer.
给出以下C代码,
int i1 = 5;
int *p1;
p = &i1;
我的理解是,p1
通过存储i1
数据的存储地址并记住该位置的数据将被解释为int
来引用int 5
(这指示了如何要读取的字节数以及如何解释读取的数据.
my understanding is that p1
references the int 5
by storing the address where i1
's data is stored and remembering that the data in that location is to be interpreted as an int
(which dictates how many bytes to read and how to interpret the read data).
地址运算符会同时产生地址和类型感知",还是因为声明p1
为int
指针之后类型感知才是隐式的?
Does the address operator yield both the address and the "type-awareness", or is the type-awareness just implicit since p1
was declared to be an int
pointer?
让我对此感到疑惑的一件事就是看到像这样的代码:
One of the things that got me wondering about this was seeing code like:
void myFunc(int *ptr);
int i = 5;
myFunc(&i);
推荐答案
&
运算符只是返回一个指向其操作数的指针.如果其操作数为int
,则结果类型将为int*
.如果其操作数为int*
,则结果类型将为int**
.例如,该程序:
The &
operator simply returns a pointer to its operand. If its operand was an int
the resulting type will be int*
. If its operand was an int*
the resulting type will be int**
. For example, this program:
#include <stdio.h>
struct test {
int a;
int b;
int d;
};
int main ( ) {
struct test foo = { 0, 0, 0 } ;
printf( "%lu\n", (unsigned long)(&foo + 2) - (unsigned long)&foo );
}
在我的机器上输出24,因为sizeof(struct test)
是12,并且已知&foo
的类型是struct test *
,所以&foo + 2
计算出两个struct test
的偏移量.
Outputs 24 on my machine because the sizeof(struct test)
is 12, and the type of &foo
is known to be struct test *
, so &foo + 2
calculates an offset of two struct test
s.
这篇关于C:地址运算符(&)是产生一个指针(地址+类型)还是仅产生一个地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!