将 compareTo 转换为 C

标签 c

因此,我正在尝试将这段代码从 Java 转换为 C,我想我大部分都搞定了,但我遇到了一些错误,我被困在下一步该做什么上。我认为我的大部分麻烦来自于在强制转换和字节移位时将 compareTo 转换为 c。

我必须将我的 void* base 转换为 char*,并使用给定的偏移算法“base + slot * size”。希望有人能帮助我了解如何解决此问题?

原始 Java:

// Insertion sort.
static <elem_t extends Comparable <? super elem_t>>
void insertion_sort (elem_t[] array, int nelem) {
    for (int sorted = 1; sorted < nelem; ++sorted) {
        int slot = sorted;
        elem_t copy = array[slot];
        for (; slot > 0; --slot) {
            int cmp = copy.compareTo (array[slot - 1]);
            if (cmp > 0) break;
            array[slot] = array[slot - 1];
        }
        array[slot] = copy;
    }
}

C 转换尝试:

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>

#include "inssort.h"


void inssort (void *base, size_t nelem, size_t size,
              int (*compar) (const void *, const void *)) {
  for(int sorted = 1; sorted < nelem; ++sorted){
    int slot = sorted;
    void* element = malloc(sizeof(size)); 
    memcpy(element, (char*)(base + slot * size), size);
    for(; slot > 0; --slot){
      int cmp = 0;
      memcpy(cmp, element - (char*)(base + slot-1 * size), size);
      if(cmp > 0) break;
      memcpy((char*)(base + slot * size), (char*)(base + slot-1 * size), size);
    }
    memcpy((char*)(base + slot * size), element, size);
  }
}

错误:

inssort.c: In function 'inssort':
inssort.c:11: warning: comparison between signed and unsigned integer expressions
inssort.c:17: error: invalid operands to binary - (have 'void *' and 'char *')
inssort.c:17: warning: passing argument 1 of 'memcpy' makes pointer from integer without a cast
/usr/include/string.h:44: note: expected 'void * restrict' but argument is of type 'int'
inssort.c:10: warning: unused parameter 'compar'
make: *** [inssort] Error 1

该函数应该接受另一个 C 文件并按升序对给定的任何内容进行排序。

最佳答案

试试这个。

for(int sorted = 1; sorted < nelem; ++sorted) {
  int slot = sorted;
  void* element = malloc(size); 
  memcpy(element, (char*)(base + slot * size), size);

  for(; slot > 0; --slot){
    //Comparison.
    int cmp = compar(elements, base+(slot-1)*size);
    if(cmp > 0) break;
    memcpy((char*)base + slot * size, (char*)base + (slot-1) * size, size);
  }
  memcpy((char*)(base + slot * size), element, size);
}

关于将 compareTo 转换为 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20342381/

相关文章:

c - 使用左键箭头向左移动,而不是使用 fgets 输入字符

c - 使用 clock() 确定函数的运行时间

c - 阻塞套接字

c - 读取输入并将其放入字符指针

c - 如何将参数传递给 HandlerRoutine?

c++ - 防止线程不必要的退出并使池保持事件状态

c - Linux C 串行程序卡住

c - C 中 if else 语句的问题

c - 第九条诫命是什么意思?

c - 函数参数如何存储在内存中?