Quantcast
Channel: C Programming Archives - QnA Plus
Viewing all articles
Browse latest Browse all 93

Change a Pointer from inside a C Function

$
0
0

We can change normal variable from inside a C function by passing the pointer of the variable. Here we’ll see how to change a pointer variable from inside a C function.

Concept is same, here we have to pass the pointer of the pointer to the function.

Code Snippet

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

void change_pointer(int** p) {

  *p = (int*)malloc(sizeof(int));
  **p = 10;
}

int main(){
  int x = 5;
  int *p = &x;
  printf("Before function call: pointer %p is pointing to %d.\n", p, *p);
  
  change_pointer(&p);
  printf("After function call: pointer %p is pointing to %d.\n", p, *p);
}

Here is the output.

Before function call: pointer 0x7ffd5234 is pointing to 5.
After function call: pointer 0x1b721605 is pointing to 10.

In main(), we have an integer pointer, p. We assigned p with the reference (or pointer) of variable x (&x).

From the first output, we can see the value of the pointer p (0x7ffd5234), and the value (5) the pointer is pointing to.

Now we want to change the pointer itself. So we passed the pointer of p (&p) to the change_pointer() function.

In the change_pointer() function, we allocated a new integer pointer and assigned that to *p. We assigned a new value (10) to the newly allocated pointer. Note that we did not assign a pointer of location variable to *p. Because the local variable will become invalidate after the change_pointer() function will return.

After the function return we can see from the second output that the pointer is changed from 0x7ffd5234 to 0x1b721605. The new pointer is pointing to a new value 10.

The post Change a Pointer from inside a C Function appeared first on QnA Plus.


Viewing all articles
Browse latest Browse all 93

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>