在Xcode中寻址C程序

当我在 Xcode中的64位Intel中编译下面的代码时,我得到了这个输出.

#include<stdio.h>
#include<limits.h>

int main(void)
{
  /* declare some integer variables */
  long a = LONG_MAX;
  long b = 2L;
  long c = 3L;

  /* declare some floating-point variables */
  double d = 4.0;
  double e = 5.0;
  double f = 6.0;

  printf("A variable of type long occupies %d bytes.",sizeof(long));
  printf("\nHere are the addresses of some variables of type long:");
  printf("\nThe address of a is: %p  The address of b is: %p",&a,&b);
  printf("\nThe address of c is: %p",&c);
  printf("\nThe address of a-b is: %ld\nvalue of a is %ld\nValue of b is %ld\nsize of pointer %ld ",(&a-&c),a,b,sizeof(&a));
  printf("\n\nA variable of type double occupies %d bytes.",sizeof(double));
  printf("\nHere are the addresses of some variables of type double:");
  printf("\nThe address of d is: %p  The address of e is: %p",&d,&e);
  printf("\nThe address of f is: %p\n",&f);

    printf("\n size long - %d",sizeof(a));
  return 0;
}
A variable of type long occupies 8 bytes.

Here are the addresses of some variables of type long:

The address of a is: 0x7fff5fbff880 
The address of b is: 0x7fff5fbff878 
The address of c is: 0x7fff5fbff870 
The address of a-b is: 2

value of a is 9223372036854775807 
Value of b is 2 
size of pointer 8 

A variable of type double occupies 8 bytes.

Here are the addresses of some variables of type double:

The address of d is: 0x7fff5fbff868 
The address of e is: 0x7fff5fbff860 
The address of f is: 0x7fff5fbff858 
size long - 8

对我来说奇怪的是a和b的地址之间的差异只有2.我希望它是8,这将与long的字节数相匹配.有谁知道为什么会这样?

我在代码中输入了一个拼写错误& a-& c,但这真的与我的问题无关.我的问题是,为什么从变量a的地址到变量b的地址只有2个字节的差异,当long为8个字节长时,我希望看到8的差异?

解决方法

差异以sizeof(long)为单位.要强制它以字节为单位,你应该先抛出两个指针:

((char *)&a-(char *)&b)

以这种方式,差异以sizeof(char)为单位,即字节数

相关文章

在有效期内的苹果开发者账号(类型为个人或者公司账号)。还...
Appuploader官网--IOS ipa上传发布工具,证书制作工具跨平台...
苹果在9月13号凌晨(北京时间)发布 iOS 16,该系统的设备可...
计算机图形学--OpenGL递归实现光线追踪
Xcode 14打出来的包在低版本系统运行时会崩溃,报错信息是Li...