将compareTo转换为C.

时间:2013-12-03 03:33:50

标签: 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文件并按升序排序。

1 个答案:

答案 0 :(得分:0)

试试这个。

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);
}