初学C语言,哪里错了,计算数组元素距离???

qq_25199377 2017-02-18 10:54:52
...全文
207 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
SuccessorZHU 2017-02-21
  • 打赏
  • 举报
回复
指针加一就已经加了c了
Davidsdu 2017-02-20
  • 打赏
  • 举报
回复
指针地址本来就是以字节为单位进行偏移计算的,所以不需要做除法了。
自信男孩 2017-02-20
  • 打赏
  • 举报
回复
int *p1, *p2; p1+1偏移多少个字节,跟该指针的类型有关;若是结构体指针,那么p+1,其在内存中偏移的长度即sizeof(结构体名);
mhysmile888 2017-02-20
  • 打赏
  • 举报
回复
数组名字代表首地址,两个相同数据类型的地址想减(数组)返回的是数组距离乘sizeof(数据类型)
赵4老师 2017-02-20
  • 打赏
  • 举报
回复
Pointer Arithmetic Additive operations involving a pointer and an integer give meaningful results only if the pointer operand addresses an array member and the integer value produces an offset within the bounds of the same array. When the integer value is converted to an address offset, the compiler assumes that only memory positions of the same size lie between the original address and the address plus the offset. This assumption is valid for array members. By definition, an array is a series of values of the same type; its elements reside in contiguous memory locations. However, storage for any types except array elements is not guaranteed to be filled by the same type of identifiers. That is, blanks can appear between memory positions, even positions of the same type. Therefore, the results of adding to or subtracting from the addresses of any values but array elements are undefined. Similarly, when two pointer values are subtracted, the conversion assumes that only values of the same type, with no blanks, lie between the addresses given by the operands.
  • 打赏
  • 举报
回复
不需要除,加关注,我也学C/C++,一起学习。
zzmlake 2017-02-18
  • 打赏
  • 举报
回复
p2-p1结果是1,不是4 1/4你输出结果肯定是0
ooolinux 2017-02-18
  • 打赏
  • 举报
回复
p+1指向p的下一个元素,就容易知道两个指针相减了。
paschen 2017-02-18
  • 打赏
  • 举报
回复
指针相减得到的本身就是这种类型元素的个数,而不是字节数,所以不用再除以c
ooolinux 2017-02-18
  • 打赏
  • 举报
回复
这个确实容易弄错。

69,382

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧