I believe i have a fair understanding of pointers. What i don't understand or rather if i'm under estimating the powerfulness of pointers. So basically we can by-pass call by value restrictions, they can be used as part of linked lists but what else?
I have come to conclusion that pointers offer the following benefits?
- We can dynamically modify whatever the pointer is pointing to. So for example we could have a method which does something and modify the contents of the pointed value, we can then print the value in the main method by de-referencing the pointer and finding out what its pointing *TO* (i.e. *xPtr = 2) makes x =2 if *xPtr = &x (if *xPtr points to X), rather than using global variables (which are bad).
- They're the equivalent of getters and setters in java (or kind of??)
And i've also written something small to demonstrate my basic understanding. Please correct me if i'm wrong:
Also what stumps me is the following:Code:#include <stdio.h> void calculate(int *xPtr); int main() { int x = 0; int *xPtr; // Create a pointer and a memory location is allocated. xPtr = &x; *xPtr = 2; //calculate(&x); // Pass a reference to the variable x, which will make xPtr point to x printf("%d", x); // print what x contains printf("%d", *xPtr); // print what xPtr is pointing to in this case x. return 0; } void calculate(int *xPtr) { *xPtr = 2; //set whatever xPtr is pointing to (x) to 2. }
If i pass a reference of x to calculate it makes xptr point to X and sets xptr to 2 which makes X 2 since xptr is pointing to x now. But for some reason i can't de-reference *xPtr and print it the program just crashes ?
Code:#include <stdio.h> void calculate(int *xPtr); int main() { int x = 0; int *xPtr; // Create a pointer and a memory location is allocated. //xPtr = &x; calculate(&x); // Pass a reference to the variable x, which will make xPtr point to x printf("%d", x); // print what x contains printf("%d", *xPtr); // print what xPtr is pointing to in this case x. return 0; } void calculate(int *xPtr) { *xPtr = 2; //set whatever xPtr is pointing to (x) to 2. }



LinkBack URL
About LinkBacks



And you try to assign it value which is reference of x.