How are pointers in C language incremented differently calculated?

In C language, the increment operation of a pointer is based on the data type that the pointer is pointing to. When a pointer is incremented, it moves one size of the data type forward.

For example, if a pointer points to data of type int, when the pointer is incremented by 1, it will move backward by the size of an int.

Here is an example:

#include <stdio.h>

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int *ptr = arr; // 将指针指向数组的第一个元素

    printf("ptr 指向的值:%d\n", *ptr); // 输出 1

    ptr = ptr + 1; // 执行指针加1操作

    printf("ptr 指向的值:%d\n", *ptr); // 输出 2

    return 0;
}

In the example above, we defined an integer array called arr and pointed ptr to the first element of the array. Then, by executing ptr = ptr + 1, we moved the pointer one integer size, which is 4 bytes. Finally, we output the value that ptr is pointing to, which is the second element of the array, 2.

It is important to note that the increment operation of a pointer is based on byte offsets, not index values. Therefore, when a pointer points to an array, adding 1 does not necessarily equal adding 1 to the index.

bannerAds