Skip to main content

Accessing Pointers in C

Accessing Pointers

In C, you can access pointers using the dereference operator *.

The * operator is used to obtain the value that the pointer is pointing to, which is called "dereferencing" the pointer.

Example 1

#include <stdio.h>

int main()
{
int num = 10;
int *ptr = &num;

printf("Value of num: %d\n", num); // Output: Value of num: 10
printf("Address of num: %p\n",
&num); // Output: Address of num: 0x7fffbe14befc
printf("Value of ptr: %p\n", ptr); // Output: Value of ptr: 0x7fffbe14befc
printf("Value of the variable pointed to by ptr: %d\n",
*ptr); // Output: Value of the variable pointed to by ptr: 10

*ptr = 20; // Update the value of num using the pointer

printf("New value of num: %d\n", num); // Output: New value of num: 20

return 0;
}
Output:

Explanation

  • We declare and initialize an integer variable num, and define a pointer variable ptr that points to the address of num.
  • We then use printf() statements to output the value of num, the address of num, the value of ptr, and the value of the variable pointed to by ptr (i.e., the value of num).
  • To update the value of num using the pointer, we simply use the * operator to dereference the pointer and assign a new value to it, like this: *ptr = 20;.
  • This changes the value of num to 20.

Example 2

#include <stdio.h>

int main()
{
char str[] = "Hello, world!";
char *ptr = str;

printf("The string is: %s\n", str); // Output: The string is: Hello, world!
printf("The pointer value is: %p\n",
ptr); // Output: The pointer value is: 0x7ffd3bce1b20
printf("The first character is: %c\n",
*ptr); // Output: The first character is: H

printf("\n");

return 0;
}
Output:

Explanation

  • We declare a character array str and initialize it with the string "Hello, world!".
  • We then define a pointer variable ptr and initialize it to point to the first element of the str array.
  • We use the printf() function to output the value of the string, the value of the pointer, and the first character of the string (which is obtained by dereferencing the pointer with the * operator).
  • We then use pointer arithmetic to iterate through the string using a while loop. Inside the loop, we output each character in the string by dereferencing the pointer and incrementing it to point to the next character.
  • The loop continues until the null character \0 is reached, which signals the end of the string.