Home > Mobile >  C pointer function implementation for a class within class
C pointer function implementation for a class within class

Time:03-31

My header file "DoublyLinkedLists" looks like this

class DoublyLinkedLists{
private:
    struct element{
        int key;
        struct element *prev, *next;
    };
    element* head = NULL;
    element* tail = NULL;
public:
    void insertToHead(int insert);
    element *find(int insert);
 
};

In the cpp file that includes "DoublyLinkedLists" header, I implemented my function(insert to head) like this:

void DoublyLinkedLists::insertToHead(int insert){
  //some code
}

I've tried, but doesnt work

DoublyLinkedLists::element* find(int insert){
//code
}

But how can I implement a function "element *find(int insert)" in a cpp file that returns a pointer? Where must I write "DoublyLinkedLists::" that specifies from where I am taking a function, or must I write something else.

I have absolutely no idea what I'm doing. I'm new to object oriented C programming and any help would be really appreciated.

CodePudding user response:

Here is a sample implementation what you are supposed to do. I don't know if tail->next == head so I check tail seperately.

DoublyLinkedLists::element* DoublyLinkedLists::find(int insert)
{
    element* current = head; // Our current node we are checking.
    while(current != tail) // as long as we aren't at the end do
    {
        if (current->key == insert) // check if the current is the one we are looking for
            return current; // return it 
        current = current->next; // else go to the next element and repeat
    }
    if (tail->key == insert) // at least we check the tail
        return tail;
   return NULL; // if "insert" is not in our list we return NULL
}

You wrote element *find(int insert) I want to point out that the * is linked to element you return a pointer of element. It is more clear if you change the function signature to element* find(int insert)

Edit: Some pointer explanation. What is a pointer? Every pointer is either 4-bytes long (32 bit) or 8-bytes long. A pointer holds a memory address. The type of pointer (int*, double*, element*, ...) tells the compiler 1) how many bytes to read on the given address and 2) how to interpret them.

Example:

int i = 100; // Let's say i is on adress 0x00000004
int* pI = &i; // pI = 0x00000004 (!) pI is exacly only the address not the value

std::cout << pI; // output: "0x00000004"
std::cout << *pI; // output: 100;

*pI simply tells the compiler "go to adress 0x00000004, take sizeof(int)(4) bytes and trat them as integer." So the compiler takes bytes 0x00000004 to 0x00000008.

CodePudding user response:

My question was poorly written, but all I've been looking was for a syntax of the function find.

DoublyLinkedLists::element *DoublyLinkedLists::find(int insert){
 //here is original code, but its quite long
  return nullptr;
}
  • Related