加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在Xcode中寻址C程序

发布时间:2020-12-14 18:55:25 所属栏目:百科 来源:网络整理
导读:当我在 Xcode中的64位Intel中编译下面的代码时,我得到了这个输出. #includestdio.h#includelimits.hint main(void){ /* declare some integer variables */ long a = LONG_MAX; long b = 2L; long c = 3L; /* declare some floating-point variables */ doub
当我在 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: %ldnvalue of a is %ldnValue of b is %ldnsize of pointer %ld ",(&a-&c),a,b,sizeof(&a));
  printf("nnA 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: %pn",&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)为单位,即字节数

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读