c - 在 Xcode 中为 C 程序寻址

标签 c xcode pointers

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

#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

令我感到奇怪的是,ab 的地址之间的差异仅为 2。我希望它是 8,这与long 的字节数。有谁知道这是为什么?


我在减去 &a-&c 的代码中确实有错字,但这确实与我的问题无关。我的问题是为什么从变量 a 的地址到变量 b 的地址只有 2 个字节的差异,而 long 是 8 个字节长,而我希望看到 8 个字节的差异?

最佳答案

指针算法是基于它指向的类型的大小而不是字节,这个引用 Pointer Arithmetic很好地涵盖了主题,您还有一个错字:

(&a-&c)

您实际上是从a 中减去c

这也是未定义的行为,因为仅当指针指向同一数组时才定义指针减法,请参阅 C11 draft standard 中的 6.5.6/9 部分:

[...] When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object;[...]

6.5.6/8 部分也相关:

[...] If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined. [...]

关于c - 在 Xcode 中为 C 程序寻址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18039352/

相关文章:

java - 有没有有效的方法使用 JNA 读取动态大小共享内存段?

c - 在内核启动时分配(静态)内存

c - 性能 AVX-512 与 MIC 上的自动矢量化(英特尔至强融核协处理器)

xcode - 如何在 Xcode 中设置特定的预编译头文件?

arrays - 将数组分配给 int 指针时出现警告 : initialization of 'int *' from ' int' makes pointer from integer without a cast,

c - 传递数组作为参数 C

c - 负值转换为其对应的正值

ios - 可快速滚动全屏 View

xcode - Xcode 4 在哪里隐藏开发中应用程序的首选项 plist 文件

c - 使用宏初始化通过引用传递的结构