Detailed Explanation of Arrays, Array Names, and Pointers in C Language

In C language, an array name can be regarded as a pointer to the first element of the array. Here are some detailed explanations about array names in C language:

1. The array name is a pointer constant

In C language, the array name is a pointer constant pointing to the first element of the array, that is, it stores the address of the first element of the array and cannot be modified. For example:

int a[] = {
    
    1, 2, 3};
int *p = a;   // 等价于 int *p = &a[0];

In the above code, we use the array name a to initialize a pointer p, and p stores the address of the first element of the array. It should be noted that both a and &a[0] are pointers to the first element of the array, and they are equivalent here.

2. Array names can be used as function parameters

In C language, array names can be passed as function parameters,It is automatically converted to a pointer to the first element of the array. For example:

void print_array(int a[], int n) {
    
    
    for (int i = 0; i < n; i++) {
    
    
        printf("%d ", a[i]);
    }
    printf("\n");
}

int main() {
    
    
    int a[] = {
    
    1, 2, 3};
    print_array(a, sizeof(a) / sizeof(int));
    return 0;
}

In the above code, we define a function called print_array, which accepts an integer array a and the size of the array n as parameters. Inside the function, we use the array name a to access the elements in the array and print them out.

3. The difference between array name and pointer

Although array names and pointers look similar in some contexts, there are some key differences between them. Specifically:

The array name is a pointer constant and cannot be modified, but the pointer can be reassigned; the
array name cannot use the increment or decrement operator to access other elements in the array, but the pointer can; the array
name can be passed as a function parameter, but Pointers need to be passed explicitly.

It should be noted that although the array name cannot use the self-increment or self-decrement operators to access other elements in the array, it can be implemented by casting the array name to a pointer type. For example:

int a[] = {
    
    1, 2, 3};
int *p = (int *)a;  // 将数组名 a 强制转换为 int 类型的指针
printf("%d\n", *(p + 1));   // 输出数组中的第二个元素(2)

In the above code, we cast the array name a to a pointer of type int, and then use the pointer p to access the second element in the array. It should be noted that this method is not recommended.

Guess you like

Origin blog.csdn.net/weixin_45172119/article/details/129767216