Technology Programming

What is a pointer in C?

1 Answer
1 answers

What is a pointer in C?

0

In C, a pointer is a variable that stores the memory address of another variable. It "points" to the location in memory where a value is stored rather than storing the value directly.

Here's a breakdown of key aspects:

  • Declaration: Pointers are declared using an asterisk (*) before the variable name. The type declaration specifies the type of data the pointer will point to. For example: int *ptr; declares a pointer named 'ptr' that can store the address of an integer variable.
  • Address-of Operator: The & operator (address-of operator) is used to get the memory address of a variable. For example: int x = 10; ptr = &x; assigns the address of 'x' to the pointer 'ptr'.
  • Dereference Operator: The * operator (dereference operator) is used to access the value stored at the memory address held by the pointer. For example: int value = *ptr; retrieves the value stored at the address pointed to by 'ptr' (which is the value of 'x', i.e., 10) and assigns it to 'value'.
  • Uses:
    • Dynamic memory allocation (using functions like malloc and calloc). GeeksForGeeks
    • Passing arguments by reference to functions. This allows functions to modify the original variables passed to them. TutorialsPoint
    • Working with arrays and strings. Pointers can be used to efficiently iterate through arrays. TutorialsPoint
    • Creating data structures like linked lists, trees, and graphs.

Example:


 #include <stdio.h>
 

 int main() {
  int x = 10;
  int *ptr;
 

  ptr = &x;  // ptr now holds the address of x
 

  printf("Value of x: %d\n", x);
  printf("Address of x: %p\n", &x);
  printf("Value of ptr: %p\n", ptr); // ptr stores the address of x
  printf("Value pointed to by ptr: %d\n", *ptr); // Dereferencing ptr to get the value of x
 

  *ptr = 20; // Modifying the value at the address pointed to by ptr (which is x)
  printf("New value of x: %d\n", x); // x is now 20
 

  return 0;
 }
 

In this example, changing the value through the pointer ptr also changes the value of the original variable x because they both refer to the same memory location.

Wrote answer · 3/14/2025
Karma · 40

Related Questions

What is Scratch?
What does the forward command do?
What is indentation? List the types of indentation.
Write a Scilab code to define a complex number in Scilab?
Write a Scilab code to determine a unit vector in Scilab?
Write a Scilab code to evaluate the magnitude of a vector in Scilab?
Write a Scilab code to perform subtraction of two vectors in Scilab?