Hi I am just learning pointers in C. I made an example program to test how they work. The program works and does what I thought it would. My question is this. My comments are how I thought that the program works. I need to make sure that what I said is true. I am pretty sure I understand what is happening but have no one to check my work.
Code:
/*
Pointer practice using function calls. Here I set up two variables
(a) and (b). Then two pointers (pa to point at a) and (pb to point at b)
next I built two functions that will update the value in (a) and (b)
using the pointers (pa) and (pb). Notice that I do not have to use the
& symbol in the scanf because the (v) and (w) are already pointers pointing
to the address of (a) and (b) via (pa and (pb).
*/
#include <stdio.h>
void ChangeIt ( int *x, int *y );
void UserChange ( int *v , int *w );
int main (void){
int a; // Initialize a
int b; // Initialize b
int* pa; // Initialize pointer pa
int* pb; // Initialize pointer pb
pa = &a; // pa = address of a set the pointer to point
pb = &b; // pb = address of b set the pointer to point
*pa = 10; // place 10 in (a) via dereferencing pa
*pb = 20; // place 20 in (b) via dereferencing pb
printf ( " a = %d: b = %d:\n", a, b); // print what is in a and b
ChangeIt ( pa ,pb );// This calls ChangeIt with the address for a and b
printf ( " a = %d: b = %d:\n", a, b); //print the result of ChangeIt
UserChange ( pa , pb);// This uses the same technique as ChangIt
printf ( " a = %d: b = %d:\n", a, b);
return 0;
}
void ChangeIt ( int *x, int *y ){
*x = *x +5; // add 5 to the value at the adress pointed to by x >> a
*y = *y - 8;// subtract 8 from the value at the address pointed to by y >> b
}
void UserChange ( int *v , int *w ){
printf ( "Enter a new number for a:");
scanf ( "%d", v ); // v is already a pointer so no & is needed
printf ( "\nEnter a new number for b:");
scanf ( "%d", w); // v and w point to the pointer pa and pb which point to a and b
}
I know I could have change this
Code:
ChangeIt ( pa ,pb );
to
Code:
ChangeIt ( &a, &b );
and done away with pa and pb. But I wanted to play around with dereferencing as in
Code:
*pa = 10; // place 10 in (a) via dereferencing pa
*pb = 20; // place 20 in (b) via dereferencing pb