C Programming: Understanding Array Pointers and Pointer Arithmetic
The code snippet demonstrates pointer arithmetic and how it can be used to access elements within a 2D array in C programming. The code initially has a syntax error but is corrected below:
int main()
{
int aa[2][5] = {1,2,3,4,5,6,7,8,9,10};
int *p1 = (int *)(&aa + 1);
int *p2 = (int *)(*(aa + 1));
printf('first_data=%d, second_data=%d\n', *(p1-1), *(p2-1));
}
The corrected code outputs the following:
first_data=10, second_data=6
Here's a breakdown of the code and why it outputs these values:
-
aais a 2D array: It has 2 rows and 5 columns, initialized with the values 1 to 10. -
&aais a pointer to the entire array: Its type isint (*)[2][5]. This pointer points to the starting address of the arrayaain memory. -
&aa + 1: This expression performs pointer arithmetic, adding the size of the entireaaarray to&aa. The result is a pointer to a memory address just beyond the end of the array. -
int *p1 = (int *)(&aa + 1): The pointer&aa + 1is cast to anint*pointer, allowing us to treat the memory at that address as an array of integers. This essentially lets us access the memory locations beyond the end of the arrayaaas if they were part of the array. -
*(aa + 1): This expression accesses the second row of theaaarray. Sinceaais a 2D array,*(aa + 1)effectively dereferences the pointer to the second row, resulting in a pointer to the first element of the second row (aa[1][0]). This pointer is also of typeint*. -
int *p2 = (int *)(*(aa + 1)): Similar to the previous step, the pointer to the second row is cast to anint*pointer, allowing us to treat it as a regular integer pointer. -
*(p1 - 1): This expression points to the last element of the first row ofaa, which is10. Sincep1points to the memory address beyond the end of the array, subtracting1makes it point to the last element of the first row. -
*(p2 - 1): This expression points to the first element of the second row ofaa, which is6. Similar top1,p2points to the first element of the second row. Subtracting1makes it point to the element before the first element of the second row.
By using pointer arithmetic and casting, the code effectively accesses elements of the array aa that are logically outside the bounds of the array, demonstrating the flexibility and potential for error in pointer manipulation in C.
原文地址: https://www.cveoy.top/t/topic/lKNw 著作权归作者所有。请勿转载和采集!