2

让我们考虑这段代码:

char arr[10];
char *ptr1 = &arr[0];
char *ptr2 = &arr[5];

或者

int i;
char *ptr1 = &i;
char *ptr2 = ptr1 + 1;

显然,这两个指针指向同一个对象。但是有没有办法在代码中确定这一点?是否可以编写这样的函数?

// Returns true if p1 and p2 points to the same object and false otherwise
bool same_object(void *p1, void *p2) {
    if(<condition>) 
        return true;
    return false;
}

我怀疑这是不可能的,因为您不能仅从指针中检索数组的大小,但我想确定是否有我可能忽略的东西。

4

1 回答 1

1

如果您不传递对象地址和大小,或者将它们存储在文件范围变量中,那么这是不可能的。

如果您将对象及其大小传递给函数,那么这将是完全可能的。对于通用对象(无论是标量、聚合还是联合),类似的东西是明确定义的:

bool same_object (size_t         objsize, 
                  const uint8_t  obj [objsize], // pass any object cast to const uint8_t* here
                  const void*    p1, 
                  const void*    p2)
{
  uintptr_t start = (uintptr_t)obj;
  uintptr_t end   = start + objsize;
  uintptr_t i1    = (uintptr_t)p1;
  uintptr_t i2    = (uintptr_t)p2;

  return i1 >= start && 
         i1 < end    && 
         i2 >= start && 
         i2 < end;
}

这是在外来系统不会实现uint8_t而普通系统将uint8_t作为字符类型实现的假设下。

于 2021-01-20T09:57:43.580 回答