Original Code:
/*
* This program demonstrates the basics of pointers.
* It demonstrates:
* 1) What pointers do
* 2) Pointing to an array
* 3) Pointers in function parameters
*/
#include<stdio.h>
void basicPointerStuff();
void pointerArithmetic();
void pointersInParameters1();
void pointersInParameters2();
int main()
{
basicPointerStuff();
pointerArithmetic();
pointersInParameters1();
return 0;
}
/*
* This function demonstrates the VERY basics of pointers.
* They are variables which POINT to another variable.
* If you do Java, they somewhat resemble a reference variable pointing to an object...
*/
void basicPointerStuff()
{
int x = 57;
int *ptr = &x; // The POINTER variable
printf("Value of x: %d\n", x);
printf("Value of ptr: %p\n", ptr);
/*
* A reference variable in Java contains bits that tell the program how to access the object it is referring to.
* It's sort of the same for pointers in C.
*/
printf("What does ptr point to? %d\n", *ptr); // Watch out for the asterisk!
}
/*
* In this function, ptr points to an array.
* If you increment ptr, it points to the next element in the array.
*/
void pointerArithmetic()
{
int x[5] = {1, 2, 3, 4, 5};
int *ptr = x; // Note that there is NOT an "&"
printf("%d\n", *ptr);
printf("%d\n", ++*ptr);
printf("%d\n", ++*ptr);
}
/*
* C, like Java, is PASS BY VALUE.
* That means that if a function uses a value passed to it via its brackets and changes it, the variable with the original value is NOT affected.
* But since pointers POINT to a variable, a function can CHANGE the value of a variable in a different function using a pointer.
* This part of the program demonstrates how this is done.
*/
void pointersInParameters1()
{
int x = 5;
int *ptr = &x;
printf("Value of x: %d\n", x);
pointersInParameters2(ptr);
printf("Now x is: %d\n", x);
printf("(Cool init?!)\n");
}
void pointersInParameters2(int *num)
{
*num += 5;
/*
* Although num is not the same pointer as ptr, they both POINT to the variable x.
* So you can directly change the value of x, as shown above.
*/
}
Output:
Value of x: 57
Value of ptr: 0x7fff62858eac
What does ptr point to? 57
1
2
3
Value of x: 5
Now x is: 10
(Cool init?!)
No comments:
Post a Comment