给整形变量地址加1,为什么不是偏移了1个字节?

BAO BAO 2017-10-25 06:24:45


字符数组 首地址+1 每次 都是偏移1字节

我试着用 int类型的 地址加1 可每次竟然偏移了4字节

如果不用 字符型指针 指向这个整形变量的地址,有什么办法能每次偏移一个字节吗?
就是 直接用&b 怎么写?
...全文
1985 9 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
jena_wy 2017-10-31
  • 打赏
  • 举报
回复
地址加1,就是当前类型的地址加一,如果想偏移1个字节,可以转换成char *
JasonHuo_ 2017-10-28
  • 打赏
  • 举报
回复
因为在你当前的环境下,int类型系统会默认为4个字节的内存大小,即long int类型;当int *p;p=0;p++;后所指向的地址偏移实际上加了4个字节,刚刚好是一个int的内存大小
csdnwjj 2017-10-27
  • 打赏
  • 举报
回复
变量地址加一,是指sizeof (变量类型) 个字节, 建议你想的话可以用位段试试,用位段可以指定一个变量占几个字符
赵4老师 2017-10-26
  • 打赏
  • 举报
回复
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.
xian_wwq 2017-10-26
  • 打赏
  • 举报
回复
3楼正解, 强制转到char* 再+1就是对字节的操作
大尾巴猫 2017-10-26
  • 打赏
  • 举报
回复
指针的加减操作,和指针的类型相关的,想一次+1偏移一个字节,只能把指针强行转换成char*
paschen 2017-10-26
  • 打赏
  • 举报
回复
你这里是给一个指针(int*)进行加法运算,指针的加法运算是这样:指针+N 相当于移动 N*sizeof(T),T是指针指向的对象类型
自信男孩 2017-10-26
  • 打赏
  • 举报
回复
注意&b是值整个类型的地址,&b+1就是偏移sizeof(int)个字节; 比如
int *p = &b; p++//即p = p+1,那么就是偏移sizeof int个字节
还有

char a[2];
a++;    /*偏移一个字节*/
&a++;    /*偏移sizeof(char) * 2个字节,即偏移一个数组长度*/
真相重于对错 2017-10-26
  • 打赏
  • 举报
回复
+1是指+1个变量类型的长度
xiaohuh421 2017-10-26
  • 打赏
  • 举报
回复
指针变量的+1, 是增加指针所指向的类型的字节数. int *p; p+1则是增加4字节 short *p; p+1则是增加2字节 以此类推.

70,023

社区成员

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

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