Search code examples
cpointerslinked-listdouble-pointer

Two different pointer syntax in C which one is right and what's the difference between the two?


I understand the concept of pointers and that we use them in functions to optimize the space we use.
What I don't get is the syntax when using them in functions.

Example 1:

void fun(int * a)//that means we declared a pointer to an integer type a
{
  *a+=1; 
}
fun(&b);//calling the function for int b=10;

Example 2:

void fun(int * a)//that means we declared a pointer to an integer type a
{
  a+=1;
}
fun(&b);//calling the function for int b=10;

Question: which one is right and if they are both right what's the difference between the two?

EDIT After AKX's answer: Why do we in a linked list do this then? Shouldn't it be **head instead of *head in the body if we want to change the value of the object and not the adress of the pointer ( double-pointer in this case )??

void push(struct node **head, int data)
{
        struct node* newnode = malloc(sizeof(struct node));
        newnode->data = data;
        newnode->next = *head;
}

push(&head,1);

Solution

  • If you have int *p, then *p is the pointed-to value, an int. *p += 1 increments that int. On the other hand, p itself is int *, the pointer. p += 1 increments the pointer, making it point to the next element of the array it points to.

    This should print 10 20 35:

    #include <stdio.h>
    void foo(int *p)
    {
         p += 1; /* increment the pointer */
        *p += 5; /* add to the pointed-to int */
    }
    
    int main(void)
    {
        int a[3] = {10, 20, 30};
        foo(&a[1]);     /* address of / pointer to a[1] */
        printf("%d %d %d\n", a[0], a[1], a[2]);
    }
    

    Here,

    struct node* push(struct node **head, int data)
    {
            struct node* newnode = malloc(sizeof(struct node));
            newnode->data = data;
            newnode->next = *head;
            return newnode;
    }
    

    head is a pointer to pointer to struct node, so *head is a pointer to struct node. That's what we want to store in a linked list usually, the pointer to the next piece of data. **head would be a struct node, the element itself, assigning from that would be making a copy of the piece of data.