C Array Pointer Assignment: Quick Guide
In C language, there are two ways to assign values to array pointers.
- Assigning values using the array name:
int arr[5] = {1, 2, 3, 4, 5};
int *ptr = arr;
In the example above, arr is an array of integers and ptr is a pointer to an integer. By assigning the array name arr to ptr, ptr points to the first element of the array.
- Can you please reword this sentence in your own words?
int arr[5] = {1, 2, 3, 4, 5};
int *ptr = &arr[0];
In this example, &arr[0] obtained the address of the first element of the array, and then assigned this address to the pointer ptr.
Regardless of the method used, the pointer “ptr” after assignment can indirectly access array elements using the pointer operator *, for example:
int firstElement = *ptr; // 访问数组的第一个元素
int thirdElement = *(ptr + 2); // 访问数组的第三个元素
In the above code, *ptr represents the value stored in the memory location pointed to by ptr, while *(ptr + 2) represents the value stored at the memory location two positions ahead of ptr, which is the third element in the array.