c - void 元素上的指针减法

标签 c pointers pointer-arithmetic

已编辑:基本上,我试图在给定一个元素的情况下确定 vector 中的下一个元素是什么。元素是连续的。下面的表达式应该将第一个元素作为前一个元素传递,并且它应该返回指向第二个元素的指针。我希望距离返回前一个指针和第一个指针之间的差值,以找到第二个元素的位置...

我有这样的表达:

int next = *(char *)v_next(vec, vec_first(vec));

然后在被调用的函数中,我有这一行以确定一个指针与另一个指针的位置..

void *v_next(const vector *vec, const void *previous) {
    ...
    void *first = cvec_first(cv);
    int distance = (char*) &previous - (char*) &first;

但是,当我比较第一个元素和第二个元素时,它返回的距离为 32。如果我将这个距离除以 char* 的大小,我得到 8。这显然太多字节无法将一个指针与另一个因此这个表达式无法找到正确的位置...

    next = (char*) vec->elems + vec->elemsz + distance;

如何让减法正常工作?

最佳答案

问题是您需要减去正确的“未衰减”类型的指针(无论您的情况如何)。请参阅以下示例:

#include <stdio.h>

int main(void)
{
    int a[] = {1, 2, 3, 4, 5}, *p, *q;

    p = a;
    q = a + 1;

    printf("Corect distance: %d\n", (int) (q - p));
    printf("Incorrect distance: %d\n", (int) ((char *)q - (char *)p));

    return 0;
}

请注意,pq 必须指向同一数组,或更准确地说(C99 6.5.6 加法运算符):

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

否则就是UB。 substaction 的结果具有实现定义的类型 ptrdiff_t(这就是我将结果转换为 int 的原因)。

关于c - void 元素上的指针减法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24725973/

相关文章:

c - 海湾合作委员会警告 : pointer arithmetic with type void *

c - 指针运算和数组 : what's really legal?

c - 将数组传递给函数时出现段错误

c - Fscanf 未使用 execl 通过管道的输出从通过 fdopen 分配的流中读取任何值

c++ - 将字符串解析为字符指针数组: char[0] contains the full string and [1] onward contains nothing

C编程: Sorting Structures with two parameters

c++ - const 指针作为类字段赋值

使用来自另一个 CSV 的操作数据创建 CSV

c - Printf 函数将 wrt 格式化为不同的值。

c++ - 为什么 2 地址之间的差异不是元素大小的倍数