不同类型指针之间的减法 [英] Subtraction between pointers of different type

查看:76
本文介绍了不同类型指针之间的减法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在内存中找到两个变量之间的距离.具体来说,我需要找到 char[] 数组和 int 之间的距离.

I'm trying to find the distance in memory between two variables. Specifically I need to find the distance between a char[] array and an int.

    char data[5];
    int a = 0;

    printf("%p\n%p\n", &data[5], &a);

    long int distance = &a - &data[5];

    printf("%ld\n", distance);

当我在没有最后两行的情况下运行我的程序时,我得到了两个变量的正确内存地址,如下所示:

When I run my my program without the last two lines I get the proper memory address of the two variables, something like this:

   0x7fff5661aac7
   0x7fff5661aacc

现在我明白了,如果我没记错的话,两者之间有 5 个字节的距离(0x7fff5661aac8、0x7fff5661aac9、0x7fff5661aaca、0x7fff5661aacb、0x7fff5661aacc).

Now I understand, if I'm not wrong, that there are 5 bytes of distance between the two (0x7fff5661aac8, 0x7fff5661aac9, 0x7fff5661aaca, 0x7fff5661aacb, 0x7fff5661aacc).

为什么我不能减去一个 (int *) 类型的指针和一个 (char *) 类型的指针.两者都是指内存地址.我应该怎么做才能计算两者之间的距离(以字节为单位)?我尝试投射两个指针之一,但它不起作用.

Why I can't subtract a pointer of type (int *) and one of type (char *). Both refer to memory address.. What should I do in order to calculate the distance, in bytes, between the two?? I tried casting one of the two pointers but it's not working.

我得到:错误:'char *' 和 'int *' 不是指向兼容类型的指针".感谢大家会帮助我

I get: "error: 'char *' and 'int *' are not pointers to compatible types". Thanks to everyone will help me

推荐答案

不,这是不可能的.

首先,您只能减去(指向)兼容"类型的指针,intchar 在这里不是兼容类型.因此减法是不可能的.

First, you can only subtract pointers of (to) "compatible" types, an int and a char are not compatible types here. Hence the subtraction is not possible.

也就是说,即使两者都是指向兼容类型的指针,那么也有以下情况.

That said, even if both are pointers to compatible type, then also, the following comes into picture.

因此,其次您不能只减去两个任意指针,它们本质上需要是同一数组(元素的地址)的一部分.否则,它会调用未定义行为.

So, secondly You cannot just subtract two arbitrary pointers, they need to be essentially part of (address for elements of) the same array. Othweise, it invokes undefined behavior.

引用 C11,章节 §6.5.6,加法运算符

Quoting C11, chapter §6.5.6, Additive operators

两个指针相减时,都指向同一个数组对象的元素,或超过数组对象的最后一个元素;结果是不同的两个数组元素的下标.[....]

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. [....]

第三,另一个重要的点,两个指针相减的结果是ptrdiff_t类型,一个有符号整数类型.

Thirdly, another important point, the result of subtraction of two pointers is of type ptrdiff_t, a signed integer type.

[...] 结果的大小是实现定义的,它的类型(有符号整数类型)是在 标头中定义的 ptrdiff_t.[...]

[...] The size of the result is implementation-defined, and its type (a signed integer type) is ptrdiff_t defined in the <stddef.h> header. [...]

因此,要打印结果,您需要使用 %td 格式说明符.

so, to print the result, you need to use %td format specifier.

这篇关于不同类型指针之间的减法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆