使用void *部分更正通用链表

时间:2017-01-04 02:21:13

标签: c pointers generics linked-list polymorphism

代码是在C中实现通用链接列表的实验。

作为void指针,它可以用于指向任何数据类型,并且所有类型的指针的大小始终相同,因此可以始终分配链表节点。需要函数指针来处理存储在void指针所指向的地址处的实际内容。

仅部分使用,char*可疑问题。

主要:

nodePtr start = createList();
// Create and print an int linked list
unsigned int_size = sizeof(int);
int arr[] = {10, 20, 30, 40, 50}, i;
for (i=0; i< 5; i++) {
  start= push(start, &arr[i], int_size);}

// Results in 10, 20,40 being stored and doesn't read 30,50!

代码:

struct node
{
  // Any data type can be stored in this node
  void  *data;
  struct node *next;
};

typedef struct node node;
typedef node* nodePtr;
typedef nodePtr* ptrNodePtr;

nodePtr head, tail;
int listSize;

nodePtr push(nodePtr head_ref, void *new_data, size_t data_size)
{

  // Allocate memory for node
  nodePtr new_node = (nodePtr)malloc(sizeof(node));

  new_node->data  = malloc(data_size);
  new_node->next = NULL;

  // Copy contents of new_data to newly allocated memory.
  // Assumption: char takes 1 byte.
  int i;
  for (i=0; i<data_size; i++)
    *(char *)(new_node->data + i) = *(char *)(new_data + i);

  // Change head pointer as new node is added at the beginning
  if (listSize ==0) {
    //printf("%d",listSize);
    head_ref = new_node;  }
  else{
    printf("%d",listSize);
    head_ref[listSize-1].next =  new_node;
  }
  listSize++;
  return head_ref;
}

nodePtr createList() {
  head = NULL;
  tail = NULL;
  listSize = 0;
  return head;
}

0 个答案:

没有答案