sizeof()运算符和Poiner声明中的问题 [英] Problem in sizeof() operator and poiner declaration
问题描述
这个问题是在我的Sem-2考试中提出的.问题要求我们提供所需的输出.
This question was asked in my Sem-2 examination. Question asked us to give the desired output.
int main(void)
{
int a[] = {10,20,30,40,50,60};
int (*p1)[2]=a , (*p2)[3]= a;
if(sizeof(p1)==sizeof(p2))
printf("%d",*(*p1+2));
if(sizeof(*p1)==sizeof(*p2))
printf("%d",*(*(p2+1)));
return(0);
}
编译器警告:
Warning: initialization from incompatible pointer type [-Wincompatible-pointer-types]
initialization from incompatible pointer type [-Wincompatible-pointer-types]
我期望的输出:20
运行时得到的输出:30
Output that I get when I run it: 30
使用:gcc(Ubuntu 7.4.0-1ubuntu1〜18.04.1)7.4.0
Using : gcc (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0
推荐答案
让我们忽略未定义的行为,找出可能发生的情况.
Let's ignore the undefined behavior to work out what is probably happening.
p1
和p2
都指向a[0]
(忽略不兼容的指针类型).
p1
and p2
are both pointing to a[0]
(ignoring the incompatible pointer types).
p1
和p2
都是指针.指向对象类型的指针通常具有相同的大小(假设是这种情况),因此sizeof(p1)==sizeof(p2)
将为true.
p1
and p2
are both pointers. Pointers to object types are generally the same size (assume this is the case), so sizeof(p1)==sizeof(p2)
will be true.
p1
的类型为int (*)[2]
,因此*p1
的类型为int[2]
.在大多数表达式中,数组将衰减为其第一个元素的指针,因此在表达式*(*p1+2)
中,*p1
将衰减为int *
并指向a[0]
.因此,*p1+2
将指向a[2]
.因此,*(*p1+2)
将与a[2]
相同,其值为30
.因此,程序将打印30
.
p1
is of type int (*)[2]
, so *p1
is of type int[2]
. In most expressions, an array will decay to a pointer to its first element, so in the expression *(*p1+2)
, *p1
will decay to an int *
and will be pointing to a[0]
. Therefore *p1+2
will be pointing to a[2]
. Therefore *(*p1+2)
will be the same as a[2]
, which has the value 30
. Therefore the program prints 30
.
当数组是sizeof
运算符的操作数时,它不会衰减到指针. *p1
的类型为int[2]
,而*p2
的类型为int[3]
,因此sizeof(*p1)==sizeof(*p2)
等效于sizeof(int[2])==sizeof(int[3])
,这是错误的.因此,不会评估第二次打印*(*p2+1)
值的printf
调用.
An array does not decay to a pointer when it is the operand of the sizeof
operator. *p1
is of type int[2]
and *p2
is of type int[3]
, so sizeof(*p1)==sizeof(*p2)
is equivalent to sizeof(int[2])==sizeof(int[3])
, which is false. Therefore the second printf
call that prints the value of *(*p2+1)
is not evaluated.
(假设第二个printf
被调用并且对*(*p2+1)
进行求值.*p2
的类型为int[3]
,在该表达式中,它衰减为指向a[0]
的int *
.因此,a[1]
.因此,*(*p2+1)
将与a[1],
相同,其值为20
.)
(Let's pretend the second printf
is called and that *(*p2+1)
is evaluated. *p2
is of type int[3]
and in this expression it decays to an int *
pointing to a[0]
. Therefore *p2+1
points to a[1]
. Therefore, *(*p2+1)
will be the same as a[1],
which has the value 20
.)
这篇关于sizeof()运算符和Poiner声明中的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!