structure pointer

click_here

Joined Sep 22, 2020
548
Any idea how to point to next node not previous node ?
You need to go to the end of the list before you add the new node - Have another read of this...
With your adding function -

'malloc' a new node. If successful (not null), give it it's int value. (Later, you want to return a failure code on fail so the code can try and recover, but hold back for now)

If the head node is empty, put the new node as the head.

If the head is not empty, start at head and iterate through the list until you find the last node. (i.e. make a temp node pointer called "current", point it to the head, and while current->next != NULL, current = current->next)

Once you are at the last node, pointed to by current, set current->next to your new node, and then make the ->next = NULL

Hope this helps :)
Also, you have a memory leak - Every bit of memory you 'alloc' you need to free.
 

click_here

Joined Sep 22, 2020
548
It can be a bit tricky at first, but you should be able to work it out-

Make a temp *node and point it to the head node.

Find the node at the end of the list (The hint is that the last node will have a NULL in its 'next')

Add your new node to temp->next

Try something :)
 

BobaMosfet

Joined Jul 1, 2009
2,211
I am badely confused how pointer to struct pass to function including dynamic memory allocation in function

This is my program and I intentionally didn't created structured member and written function. I want some experience persome to create structured and function need to test two lines written releated function in main function.

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

struct point
{

};


int main ()
{
    struct point *P = NULL;
  
    fun1(P);  // passing pointer to structure by value
    fun2(&P); // passing pointer to structure by address

    return 0;
}
.
I know pointer, function, dynamic memory allocation, and structure. I am having hard time understanding how to pass pointer to struct to function.
@Dadu .... OMG... you're making this so complicated (not your fault, you were not taught correctly how to define and declare structures). Come young JEDI, I will show you the way...

First.... STOP using 'struct' everywhere. The idiot that showed you that had now clue. The *ONLY* reason people do this is because they are too stupid to understand it is because they never defined a variable TYPE- so they have to keep telling the compiler (hey, compiler, this is a struct).... And this amateur method promulgates endlessly through the c-programming continuum..... *sigh*. (end of rant).

Your ultimate question has to do with queues. Dynamically create queues that have previous and next nodes. In order to do this, you DOUBLY must understand how to do both declarations, AND FORWARD DECLARATIONS- which few understand today.

Now, there are a few ways to manage queues- you can endlessly add to the tail of a queue, while eating the head, or you can create a finite-sized circular queue and move a head and tail pointer around (more efficient, as alloc/dealloc takes time). In fact, if you're doing embedded, you avoid alloc/dealloc as much as possible because of the overhead.

First, let's actually create a variable type so the compiler has something to work with easily in its symbol table:

Code:
typedef struct nodeFP                                           // nodeFP is a forward declaration (see below)
   {
   nodeFP   *prevNodeP;
   nodeFP   *nextNodeP;
   < payload fields>
   }node,*nodeP;
THE ONLY REASON FORWARD DECLARATIONS EXIST is so that you can reference a structure BEFORE it's fully defined. This tells the compiler, hey, remember this as a single symbol before it reaches the enclosing brace telling it the symbol is defined (and thus has a name).

Notice in the above structure how I used the forward declaration 'nodeFP', in the first 2 fields of the structure- you _ALWAYS_ put in pointer references to queue nodes as the FIRST fields in a node structure. ALWAYS. Because the only thing you can always guarantee about the structure is that it resides somewhere (it has an address), and the first two fields are pointers. You have no idea what the rest of the structure actually looks like- Somewhere during code running, somebody may have extended the structure to hand their own data onto it to keep track of in between context switching, for example. As your experience grows, you will come to realize the full ramifications of putting these fields at the top of the struct and nowhere else.

Now that you have PROPERLY defined the structure, and it's custom pointer, you can use those without throwing 'struct' around everywhere- it makes coding easier in every way because now you're doing it properly.

Code:
node   myNode = NULL;
nodeP  qHeadP = NULL;
nodeP  qTailP = NULL;
nodeP tempP = NULL;
int  i = 0;

for(i=0;i<20;i++)                                // creat circular queue with 20 nodes
   {
   qTailP = NULL;                                         // Init each time through
  
   qTailP = (nodeP)malloc(sizeof(node));                 // create next (tail) node
   if(qTailP)
      {
      if(!qHeadP)                                 // If just created first node, remember it as head
         qHeadP = qTailP;

      if(tempP)                                    // Point last tail node (if exists), to new tail node
         {
         qTailP->prevNodeP = tempP;
         tempP->nextNodeP = qTailP;
         };

      tempP = qTailP;                          // Remember last node for next go around
      };
   };

tempP = NULL;
if(qHeadP)                                        //  Close the circle
   {
   qTailP->nextNodeP = qHeadP;
   qHeadP->prevNodeP = qTailP;

   qTailP = qHeadP;                           // Shorten the snake
   };
Ok, so the above creates a circular queue of 20 nodes. Every node points to next node, and previous node. This makes it easy to deallocate nodes when done with queue.

Head and Tail pointers are equivalent to start. Whenever payload comes in, you apply that to the head pointer, and then increment the headP to the next queue element. Leave the tail alone. Your snake just grew in length. when you are ready to read from the queue, you go read the tail element and increment it to the next pointer. Each time you increment the tail, you check to see if it is equal to the head and if so, you stop. You've emptied the queue.

The idea is that you read data from the tail faster than data comes into the head. In this way, a reasonably sized queue can handle finite whatevers.

Hopefully the above will help you.

If you want to pass a struct pointer to a function do this:

Code:
int myFunc(nodeP);                              // Prototype

int myFunc(nodeP theP)                     // the function
   {
   // do something wih the node

   return(errorCode);                            // return a result if any
   }

err = myFunc(qTailP);                          // how to call the above function
Because you are passing a pointer, an ADDRESS, you're changing the original node that was passed, not a copy on the stack. The variable is copied onto the stack, but it is just a long containing an address to your node. In the function, you go through (using '->') that address to interact with the fields of the node structure. When you leave the function, the address ('theP') is thrown away off the stack frame, and you are back to your calling function with the modified node. Because the node was allocated dynamically at runtime, it exists in the heap apart from the stack.
 
Last edited:
Top