문제

I need to implement a set of functions providing various set operations such as create set, add element to set, etc. I am new to programming, however, I know how to write a function but my problem with this task is that I need to use pointers and I have no idea how to for example write a function to create a set with pointers. I am not asking for solutions, just a good explanation to get me started! Thanks

도움이 되었습니까?

해결책

Sets can be stored in various data structures such as, but not limited to, a linked list. You then need to abstract away set operations to add, remove, test for membership of elements. I advise you to read data structure related literature and do some related exercises before undertaking this small project.

다른 팁

First you need some structure to hold your pointers, it could be as simple as an array (or a linked list as Tarik suggested).

Once you have a structure you create the set functions.

E.g.

void createSet(int*** set, int maxsize)
{
  *set = malloc(sizeof(int*) * maxsize); 
}

void addPtrToSet(int** set, void* ptr, int* numberOfPointers)
{
  // check if pointer is already in array
  int i;
  for (i = 0; i < *numberOfPointers; ++i)
  {
    if (ptr == set[i]) return; // already in set
  }
  set[(*numberOfPointers)++] = ptr;
}

...

const int maxsize = 10;
int** set = 0;
int a;
char* b;
int numberOfPointers = 0;
createSet(&set, maxsize);
addPtrToSet(set, &a, &numberOfPointers);
addPtrToSet(set, &b, &numberOfPointers);
addPtrToSet(set, &a, &numberOfPointers); // will not be added to set

here assuming sizeof(int*) == sizeof(char*)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top