1

我们正在为 C 中的通用类型数据实现优先级队列。我们认为指针等之间的分配是正确的,但我们不知道如何在最后打印“元素”的 int 值。你能帮助我吗?

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

struct _pqElement{
  void** data;
  void** priority;
};

pqElement* pqElement_new(void* data, void* priority){
  pqElement* result = (pqElement*) malloc (sizeof(pqElement));
  result->data=&data;
  result->priority=&priority;
  return result;
}

static int* new_int(int value){
 int *elem=(int*)malloc(sizeof(int));
 *elem=value;
 return elem;
}

int main(int argc, char const *argv[]){
  pqElement * element = pqElement_new(new_int(1), new_int(85));
  printf("%d-%d", element->data, element->priority);
}
4

3 回答 3

1

您不需要两级指针。

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

struct pqElement{
  void *data;
  void *priority;
};

struct pqElement* pqElement_new(void* data, void *priority)
{
  struct pqElement* result = malloc(sizeof(struct pqElement));
  result->data = data;
  result->priority = priority;
  return result;
}

static int* new_int(int value)
{
  int *elem = malloc(sizeof(int));
  *elem=value;
  return elem;
}

int main(int argc, char const *argv[])
{
  struct pqElement *element = pqElement_new(new_int(1), new_int(85));
  printf("%d-%d", *(int*)element->data, *(int*)element->priority);
}

最后打印值需要以正确的方式转换指针,正如 Alexander Pane 已经提到的那样。

使用不同类型的优先级也会使队列不那么通用。您需要为排序、打印等提供不同的功能。

于 2018-06-07T10:26:39.020 回答
1

好吧,代码甚至无法编译,因为pqElement从未定义过类型,而只定义了_pqElement结构。

您也在 中使用%dprintf但您传递的参数是void**,因此您需要转换该值。

这些更改应该可以解决问题:

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

typedef struct _pqElement{
    void** data;
    void** priority;
} pqElement;

pqElement* pqElement_new(void* data, void* priority){
    static pqElement* result;
    result = (pqElement*) malloc (sizeof(pqElement));
    result->data=&data;
    result->priority=&priority;
    return result;
}

int* new_int(int value){
    static int *elem;
    elem = (int*)malloc(sizeof(int));
    *elem=value;
    return elem;
}

int main(int argc, char const *argv[]){
    pqElement *element = pqElement_new(new_int(1), new_int(85));
    printf("%d-%d\n", **((int**)(element->data)), **((int**)(element->priority)));
    //need to free the memory allocated with the malloc, otherwise there is a possibility of memory leakage!
}

这只会打印第一个元素,但您可以使用偏移量指向以下元素。

注意:正如我在代码中作为注释报告的那样,您需要释放使用 malloc 分配的内存,否则您有潜在的内存泄漏!

于 2018-06-07T10:17:15.460 回答
-1

感谢你们。我需要代码也适用于字符串,所以我这样做了:

static char* new_string(char* value){
  char* elem= malloc (sizeof(char));
  strcpy(elem, value);
  return elem
}

像这样打印出来:

 int main(int argc, char const *argv[]){
   struct pqElement *element = pqElement_new(new_string("Hello"), 85);
   printf("%s-%d", *(char*)element->data, element->priority);
 }
于 2018-06-07T10:43:01.000 回答