关于指针/数组+1 究竟是指向下一个元素还是字节

wanderer2199 2017-09-02 09:19:08
在学汇编的时候 通常+x 表示偏移x个字节;学c++时,通常数组+x表示移动x个元素 想请问下大家什么情况下是字节 什么情况下是元素..
...全文
380 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
srhouyu 2017-09-03
  • 打赏
  • 举报
回复
C++无论何时都是按元素。 指针在移动时,C++会时刻注意着指针当前的类型。若是你强制换了类型,就按照换了的算;若是你没给类型(比如void*),那它会报错。
wanderer2199 2017-09-03
  • 打赏
  • 举报
回复
引用 2楼幻夢之葉 的回复:
是对指针所表示的类型的 +x int p[10]; int *p; // p所表示的是int这个类型的指针 p+1 就相当于 p的首地址 + sizeof(int)*1 int p[10][3]; int (*p)[3]; // p所表示的是 int [3]这个类型的指针 p+1 相当于 p的首地址 + sizeof(int)*3*1 int *p对其强制转换为其他类型,如 ((char*)p) + 1; 此时相当于 p的首地址 + sizeof(char)
就是说如果不把指针强制转换成其他类型 就是按元素算?
  • 打赏
  • 举报
回复
指针+1,这个是要根据指针类型来的!!你试试 void *p;p++;看看编译通过不通过~
赵4老师 2017-09-03
  • 打赏
  • 举报
回复
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.
幻夢之葉 2017-09-02
  • 打赏
  • 举报
回复
是对指针所表示的类型的 +x int p[10]; int *p; // p所表示的是int这个类型的指针 p+1 就相当于 p的首地址 + sizeof(int)*1 int p[10][3]; int (*p)[3]; // p所表示的是 int [3]这个类型的指针 p+1 相当于 p的首地址 + sizeof(int)*3*1 int *p对其强制转换为其他类型,如 ((char*)p) + 1; 此时相当于 p的首地址 + sizeof(char)
大米粥哥哥 2017-09-02
  • 打赏
  • 举报
回复
汇编一般对字节操作 而c++一般对元素操作 说了和没说一样 c++是高级语言 和汇编这种机器语言本来就不一样

64,654

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

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