Concept
How can you check for a NULL pointer and dereference a valid pointer?
ComputerScienceOne / Passing By Reference
"Pointers NULL using the usual equality operator.\n\n1 int *ptrA = NULL;\n\n2 ...\n\n3 if(ptrA == NULL) {\n\n4 printf(\"Error: invalid memory location\n\n\");\n\n5 }\n\nDereferencing Operator\n\nOnce we have a valid pointer to a memory location, we may want to manipulate the contents of the memory it references. To do this we use the inverse operation, the dereferencing operator which again uses an asterisk. Given a pointer variable ptrA, we apply an asterisk in front of it to turn it into a regular variable. Consider the following example.\n\n1 //declare a normal integer variable\n\n2 int a = 10;\n\n3 //declare a pointer and initialize it to NULL\n\n4 int *ptrA = NULL;\n\n5\n\n6 //point ptrA to a's memory location\n\n7 ptrA = &a;\n\n8\n\n9 //change the value of the variable a using its pointer\n\n10 *ptrA = 20;\n\n11\n\n12 //now the variable a has a value of 20:\n\n13 printf(\"a = %d\n\n\", a); //prints \"a = 20\"\n\nFigure 18.1 depicts how these lines of code operate in memory. Pointers can be made to point to other variable’s memory locations. You can manipulate/access values of variables via their pointers using dereferencing."
Related Ideas
- How do you use and validate a dynamically allocated array?ComputerScienceOne · Dynamic Memory
- How does malloc() allocate memory for a dynamic array?ComputerScienceOne · Dynamic Memory
- How do you access members through a pointer to a structure?ComputerScienceOne · Selection Operators
- How do you invoke functions that accept pointer parameters?ComputerScienceOne · Passing By Reference
- How do pointers pass values by reference in C?ComputerScienceOne · Function Pointers
- How can the return value communicate errors when roots are passed by reference?ComputerScienceOne · Quadratic Roots
- How should a comparator handle an array of structure pointers with NULL values?ComputerScienceOne · Sorting Pointers to Elements
- How can pointer manipulation create a contiguous two-dimensional array?ComputerScienceOne · Contiguous 2-D Arrays