c - int * 常量转换

标签 c pointers

#include <stdio.h>

main() {
  int *i,*j;
  i = (int *) 60;
  j = (int *) 20;
  printf("%d\n", i - j);
}

这段代码的输出是什么?我用指针做了很多工作,但从未遇到过这样的代码。

最佳答案

这是未定义的行为,因为您要减去不指向同一数组对象内部的指针。

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; the result is the difference of the subscripts of the two array elements.

它也可能是其他原因导致的未定义行为,例如使用指向无效对象的指针。

I am getting an ouput of 10..but couldn't figure out how?

撇开未定义的行为不谈,如果 sizeof(int) 在您的机器上是 4,那么地址 2060< 之间确实有 10 个整数。这就是指针减法为您提供的:元素数量的差异


teppic 所述,您的 printf 是错误的。 2 个指针之间的差异是 ptrdiff_t。格式应该类似于 %td

关于c - int * 常量转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12228127/

相关文章:

c - 为什么执行此 C MPI 应用程序进行 Pi 近似时的结果总是相同?

c - 如何在 C 中为多线程使用互斥量?

C++ 函数中的局部指针

c - gcc 版本 4.6.3 上的 c 程序汇编版本

php - 警告: PHP Startup: Unable to load dynamic library apc.所以

c - 使用 fopen_s 打开文件流时出现未处理的异常访问冲突

c++ - 我怎样才能确保我的程序在内核模式下成功运行?

c - 如何在程序中指针输出?

c - 这是MSDN的错误吗?关于指针运算

c - sizeof(<variable>) 而不是 sizeof(<type>) 总是安全的吗?