计算并输出两个指针的差值

标签 c pointers

以下 c 程序的输出是 1。有人可以解释一下吗?

#include<stdio.h>
#include<string.h>
int main(){
    int a = 5,b = 10,c;
    int *p = &a,*q = &b;
    c = p - q;
    printf("%d" , c);
    return 0;
}

最佳答案

程序调用了未定义的行为。指针减法必须使用指向同一数组元素的指针来完成。

来自 C 标准:

(C99, 6.5.6p9) "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 [...]"

关于计算并输出两个指针的差值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20800169/

相关文章:

c++ - 各种操作系统的语言环境格式

c - 寻找制作非线性、多输入程序的建议 (C)

php - 将 C 转换为 PHP?

c++ - "hello"和 {"hello"} 有什么区别?

c - 在 memcpy 期间取消引用 void * 指针,想知道如何解决这个问题?

c - Memcpy 在 C 低级程序中不起作用

python - 使用一个 C 程序运行 python 脚本(不同的 python 版本)

c++ - 多维数组如何存储在内存中?

c - 是否可以将 C 指针初始化为 NULL?

c - 为什么以及如何运作?