找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 308|回复: 2

Question4.4:I'm trying to use pointers to manipulate an array of ints

[复制链接]

210

主题

371

回帖

0

积分

管理员

积分
0
发表于 2013-7-2 16:31:04 | 显示全部楼层 |阅读模式
Q: I'm trying to use pointers to manipulate an array of ints. What's wrong with this code?
                             int array[5], i, *ip;
                             for(i = 0; i < 5; i++)
                                         array这里是array数组,我这里显示不出来= i;
                             ip = array;
                             printf("%d\n", *(ip + 3 * sizeof(int)));I expected the last line to print 3, but it printed garbage.
A: You&#39;re doing a bit more work than you have to, or should. Pointer arithmetic in C is always automatically scaled by the size of the objects pointed to. What you want to say is simply
                         printf("%d\n", *(ip + 3));    /* or ip[3] -- see Q 6.3 */
which will print the third element of the array. In code like this, you don&#39;t need to worry about scaling by the size of the pointed-to elements--by attempting to do so explicitly, you inadvertently tried to access a nonexistent element past the end of the array (probably array[6] or array[12], depending on sizeof(int) on your machine).
See, however, question 7.19b.

210

主题

371

回帖

0

积分

管理员

积分
0
 楼主| 发表于 2013-7-2 16:52:27 | 显示全部楼层
问题:我试图用指针操作一些列整形数(这里改成"操纵一个整型数组"),这个代码有什么问题?
                int array[5], i, *ip;
                             for(i = 0; i < 5; i++)
                                         array这里是array数组,我这里显示不出来)= i;                             
                              ip = array;
                             printf("%d\n", *(ip + 3 * sizeof(int)));
我期望是打印出3的,结果打印出的值是乱码。
回答:你做了很多的无用功。在C语言中,指针是自动的衡量它所指向的值的的空间大小的。你只需要这样就可以了:
          printf("%d\n", *(ip + 3));    /* 或者 ip[3] -- 参考问题6.3 */
它将会打印出数组的第三个元素。在类似的代码中,你不需要担心衡量指针所指向的元素的空间大小。如果按照问题中做如此清晰的描述,那么你将会不经意的访问到了超出数组的范围的不存在的值(很可能是array[6]或者array[12],这个取决于你的机器的sizeof(int))。
参考问题7.19b。




205

主题

173

回帖

6925

积分

论坛元老

积分
6925
发表于 2013-7-2 16:59:53 | 显示全部楼层

问题:我试图用指针操纵一个整型数组,下面这个代码错在哪里?
……
……
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

果子博客
扫码关注微信公众号

Archiver|手机版|小黑屋|风叶林

GMT+8, 2026-2-1 13:54 , Processed in 0.071847 second(s), 20 queries .

Powered by 风叶林

© 2001-2026 Discuz! Team.

快速回复 返回顶部 返回列表