c++ - 如何使用无效*

标签 c++ void-pointers

我正在实现一个简单的 merge 函数,但我卡住了,因为编译器给我无法解释的错误。这是我的 merge 函数:

void merge(void *a, int beg, int middle, int end, int (*cmp)(const void*, const void*
{
  std::stack<void*> first;
  std::stack<void*> second;

  for(int i = beg; i < middle; i++) {
   first.push(a+i);
  }
  for(int i = middle; i < end; i++) {
    second.push(a+i);
  }

  for(int i = beg; i < end; i++) {
    if(first.empty()) {
      void *tmp = second.top();
      second.pop();
      a+i = tmp;
    } else if(second.empty()) {
      void *tmp = first.top();
      first.pop();
      a+i = tmp;
    } else if(cmp(first.top(), second.top())) {
      void *tmp = first.top();
      first.pop();
      a+i = tmp;
    } else {
      void *tmp = second.top();
      second.pop();
      a+i = tmp;
    }
  }
}

这里是错误:

sort.h: In function `void merge(void*, int, int, int, int (*)(const void*, const void*))':
sort.h:9: error: pointer of type `void *' used in arithmetic
sort.h:12: error: pointer of type `void *' used in arithmetic
sort.h:19: error: pointer of type `void *' used in arithmetic
sort.h:19: error: non-lvalue in assignment
sort.h:23: error: pointer of type `void *' used in arithmetic
sort.h:23: error: non-lvalue in assignment
sort.h:27: error: pointer of type `void *' used in arithmetic
sort.h:27: error: non-lvalue in assignment
sort.h:31: error: pointer of type `void *' used in arithmetic
sort.h:31: error: non-lvalue in assignment

谁能帮帮我? TIA。

最佳答案

void* 无法进行指针运算,因为 void 没有大小,而指针运算需要根据类型的大小计算内存地址。

如果您希望begmiddleend 来表示字节偏移,您应该使用 char 指针代替(一个 char 是一个字节)。

如果你想写一个适用于任何类型的泛型函数,不要使用void指针,而是使用模板:

template <typename t>
void merge(T *a, int beg, int middle, int end, int (*cmp)(const T*, const T*))
{
    // ...
}

关于c++ - 如何使用无效*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11247584/

相关文章:

c++ - c语言中的远函数指针是什么,它的语法是什么?

c++ - void * 转换为 int 语法的问题

c - 在 C 中将 const 赋值给非常量

c - Malloc 和 Void 指针

c++ - cairo + freeglut 组合错误

C++ 重载模式 : call resolution with mutable lambda

c++ - 如何增加字符指针?

c++ - 整数环绕?

转换 void 指针并使用格式说明符打印

c++ - C++ 共享数据成员指针