C中奇怪的输出问题 [英] strange output issue in c

查看:92
本文介绍了C中奇怪的输出问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

1)  #include <stdio.h>
    int main()
  {
       int a[5] = {1,2,3,4,5};
       int *ptr = (int*)(&a+1);
        printf("%d %d", *(a+1), *(ptr-1));
        return 0;
   }

输出为2 5 . &a表示a[0]的地址,因此&a+1应该是a[1]的地址.因此,ptr应该保存a[1]的地址. *(a+1)将是2,但*(ptr-1)也应该是2.我不知道它如何打印5.

the output is 2 5. &a means the address of a[0] so &a+1 should be the address of a[1]. So ptr should hold the address of a[1]. *(a+1) will be 2 but *(ptr-1) should also be 2. I can't understand how is it printing 5.

推荐答案

此表达式很重要:&a+1.实际上是(&a)+1,它等于(&a)[1],它将是指向数组末尾一个元素的指针.

This expression is the important thing: &a+1. That is actually (&a)+1 which is equal to (&a)[1] which will be a pointer to one element past the end of the array.

如果我们更图形化地"看待它,它看起来像这样,并添加了相关的指针:

If we look at it more "graphically" it looks like this, with relevant pointers added:


+------+------+------+------+------+
| a[0] | a[1] | a[2] | a[3] | a[4] |
+------+------+------+------+------+
^      ^                           ^
|      |                           |
|      &a[1] (equal to *(a + 1))   |
|                                  |
&a[0] (equal to a)                 |
|                                  |
&a                                 &a+1

首先,&a的类型为int (*)[5],因此您对int *的强制转换将破坏严格的别名(导致未定义的行为).

First of all, the type of &a is int (*)[5], so your cast to int * will break strict aliasing (which leads to undefined behavior).

第二,由于ptr有效指向a[5],因此ptr - 1将指向a[4].

Second of all, since ptr is pointing, effectively, to what would be a[5] then ptr - 1 will point to a[4].

这篇关于C中奇怪的输出问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆