-2
#include <stdio.h>
#include <stdlib.h>

change (int i)
{
    int *x;
    x = &i;
    printf("%d\n",*x);
    *x = 7;
    printf("%d\n",*x);

} 

int main()
{
    int i=66 ; 
    change(i);
    printf("%d\n",i);
    return 0;
}

I'm wondering how to change a var value using pointer in a function using C.

TylerH
  • 20,799
  • 66
  • 75
  • 101
91256
  • 1

1 Answers1

0

You need to pass the variable i to the function by reference.

In C passing by reference means passing an object indirectly through a pointer to it. Thus dereferencing the pointer within the function you can change the original object pointed to by the pointer.

So your function will look like

void change (int *p)
{
    printf("%d\n",*p);
    *p = 7;
    printf("%d\n",*p);
} 

and be called like

change( &i );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335