Bifalgorithm post · Computer science one · Passing By Reference

How can you check for a NULL pointer and dereference a valid pointer?

How can you check for a NULL pointer and dereference a valid pointer? (Computer science one · Passing By Reference) — "Pointers NULL using the usual equality o…

Ideas in this flowchart

  • Pointer validation and dereferencing in C
  • Checking for NULL uses the usual equality operator.
  • The pointer ptrA is initialized to NULL.
  • The condition ptrA == NULL tests for an invalid memory location.
  • If ptrA is NULL, the program prints an invalid-memory-location error.
  • The dereferencing operator accesses the contents of a referenced memory location.
  • Dereferencing requires a valid pointer to a memory location.
  • An asterisk placed before a pointer turns it into a regular variable expression.
  • Example of assigning an address and changing a value through a pointer
  • The integer a is initialized to 10 and ptrA is initialized to NULL.
  • ptrA = &a makes ptrA point to a's memory location.
  • *ptrA = 20 changes the value stored in a to 20.
  • Printing a confirms that its value is 20.
  • Figure 18.1 depicts how these pointer operations work in memory.
  • Pointers can refer to other variables and access or manipulate their values through dereferencing.
Feed/

How can you check for a NULL pointer and dereference a valid pointer?

No cover

Channel

Computer science one

1 page

"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."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.