mercredi 1 juillet 2015

How can I pass a single pointer to a structure, inside a function and modify that structure variable?

In the below piece of code, I am able to modify the a variable used in main from the function.

#include<stdio.h>

    int main()
    {
      int *a,b=10;
      a = &b;
      printf("%d\n",*a);
      ref(a);
      printf("%d\n",*a);
      return 1;
    }

    int ref(int *a)
    {
       int b = 98;
       *a = b;
       return 1;
    }

whereas, in the below piece of code, I couldnot able to do the same.

I know that we can modify a value which is in the main, from a function by using double pointer. I also know that we can use single pointer to modify, by returning the required address to the main and getting it in the main with the same data type. I just wanted to know whether I can modify a value in the main by passing it as a parameter to the function, only as a single pointer to the (structure) variable.

Note: I have denoted the working code with the comment '//WC'. Will be very thankful if someone can explain me the same.

  //int insert(int data, Node **head) //WC
    int insert(int data, Node *head)
    {
       Node *temp, *run;
       temp = (Node *) malloc(sizeof(Node));
       temp->data = data;
       temp->next = NULL;

       //if(*head == NULL) //WC
       if(head == NULL)
       {  
          printf("1st node\n");
          //*head = temp; //WC
          *head = *temp;
       }
       else
       {
          printf("node after first\n");
          //run = *head //WC
          *run = *head;
          while(run->next != NULL)
          {
             run = run->next;
          }
          run->next = temp;
       }

       return 1;
    }
    int main()
    {
       Node *head;
       insert(10, head);
       insert(20, head);
       insert(30, head);
       insert(40, head);
       insert(50, head);

       return 1;
    }

Aucun commentaire:

Enregistrer un commentaire