'Why is the output of below code related to struct and pointers as follows?

New to C here, asking why the o/p of below code is as below

#include <stdio.h>

typedef struct a{
    int a;
} A;

void func ( A* x)
{
    printf("2. %d\n",x->a);
    A* y = (A*) malloc (sizeof(A));
    y->a = 10;
    x = y; 
    printf("3. %d\n",x->a);
}

int main() {
    // Write C code here
    A* a1 = (A*) malloc (sizeof(A));
    a1->a=5;
    printf("1. %d\n",a1->a);
    func (a1);
    printf("4. %d\n",a1->a);
    return 0;
}

Output:

  1. 5
  2. 5
  3. 10
  4. 5

I am expecting the 4th printf value to be 10 since I am passing a pointer to func and I am executing x = y in func so that x also points to the object pointed by y, but outside func a1 is still pointing to its original object. Why is this happening and how can I modify code so that a1 points to the new object created in func ? Could anyone please help



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source