简体   繁体   中英

How do I store a pointer (node) returned by a function to my main?

I currently completed my function to reverse a linked list, but when I return a pointer to the head of the new linked list I am getting errors because I am storing it wrong in my main. Can someone explain to me the proper syntax to store and print the newly linked list?

typedef struct Node {
   int val;
   struct Node * next;
}LL_t;

LL_t reverse(LL_t* ls) // passing me a head
{

   \\ my code

   return ls; // pretty sure this is how I return the new head node 
}

int main() {

 \\ my code

   LL_t *p = reverse(head); // not working, giving me these weird incompatible errors.

   for ( i = 0; i < 9; i++ )
   {
         printf( "*(p + %d) : %d\n", i, *(p + i));
   }
   return 0;   
}

Here is my final error after changing my variable pointer p and attempting to printf it

int *p; p = reverse(head)

Error;

main.c:42:6: warning: assignment from incompatible pointer type [enabled by default] p = reverse(head);

Edit2:

I tried tis approach, but not workin for me:

   for (p->val != NULL)
   {
        printf("%d\n", p->val);
        p->val = p->next;
   }
LL_t reverse(LL_t* ls) { }

Takes a pointer, but returns a structure. You need:

LL_t *reverse(LL_t* ls) { }

The reason you are facing issues is because your function is set up to return a LL_t node, not a pointer to it. By fixing the function declaration, your shouldnt face any other errors (at least from the provided code):

LL_t* reverse(LL_t* ls) { ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM