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 can you check for a NULL pointer and dereference a valid pointer? | ComputerScienceOne | Bifalgorithm | Bifalgorithm