user2793618
user2793618

Reputation: 312

C Passing and Reassinging Pointers in Functions

Here's the function in question. Why does x not change, despite having ptr reference it's memory address? Similarly why doesn't y change?

#include <stdio.h>


int func (int a, int *b)
{
  int *ptr = &a;
  *ptr += 5;
  ptr = b;
  *ptr -= 3;
  return a;
}

int main ()
{
  int x = 2;
  int y = 8;
  int ret = func (x, &y);
  printf ("x: %d\n", x);
  printf ("y: %d\n", y);
  printf ("ret: %d\n", ret);
  return 0;
}

Edit: yes y does change. Sorry.

Upvotes: 1

Views: 47

Answers (1)

Jacob Geigle
Jacob Geigle

Reputation: 60

int func (int a, int *b)

'a' is passed by value. Inside func() a has its own memory allocated, so anything you do to it does not affect the variable that was passed in. 'b' is a pointer to an int so changing the data at that address is still visible outside the scope of func(). Hence, x doesn't change, but y does.

Upvotes: 3

Related Questions