In C programming language, pointers are variables that store the address of another variable. There are two operators used to work with pointers: the subscriptor operator and the dereference operator.
The subscriptor operator is denoted by the []
symbol. It is used to access an element of an array through a pointer. For example, if ptr
is a pointer to an array of integers, the following code will access the third element of the array:
int *ptr = &arr[0];
int third_element = ptr[2];
The ptr[2]
expression is evaluated by first dereferencing the pointer ptr
. This means that the address stored in the pointer is converted to the value of the variable that it points to. In this case, the value of ptr
is the address of the first element of the array. The [2]
expression then accesses the third element of the array, which is located at the address ptr + 2 * sizeof(int)
.
The dereference operator is denoted by the *
symbol. It is used to get the value of the variable that a pointer points to. For example, the following code will print the value of the third element of the array:
int *ptr = &arr[0];
int third_element = *ptr + 2;
printf("%d\n", third_element);
The *ptr
expression is evaluated by first dereferencing the pointer ptr
. This means that the address stored in the pointer is converted to the value of the variable that it points to. In this case, the value of ptr
is the address of the first element of the array. The *
symbol then gets the value of the variable that ptr
points to, which is the first element of the array. The + 2
expression then adds 2 to the value of the first element of the array, and the result is printed to the console.
The subscriptor operator and the dereference operator are two powerful tools that can be used to work with pointers in C programming language. By understanding how these operators work, you can write more efficient and effective code.