fix pointer increment in matrix loop
The original code used `*matrix[i]++` in the nested loop, which incremented the pointers stored in `matrix[0]` and `matrix[1]`, causing them to point beyond the bounds of `arr1` and `arr2` after the loop. This could lead to undefined behavior if `matrix` is used later. With the new change, `matrix[0]` and `matrix[1]` remain pointing to `arr1[0]` and `arr2[0]`. The output remains unchanged, but the code is now safer and aligns with the intended behavior.
With the original version of the code:
```c
#include <stdio.h>
// matrix -> arr -> integers
// similar to 01.c but with arrays
int main() {
int arr1[] = {1, 2, 3, 4};
int arr2[] = {5, 6, 7, 8};
int* ptr1 = arr1;
int* ptr2 = arr2;
int* matrix[] = {ptr1, ptr2};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 4; j++) {
printf("%d ", *matrix[i]++);
}
printf("\n");
}
printf("\nAfter loop:\n");
printf("matrix[0] points to %p (expected arr1[4]: %p)\n", (void*)matrix[0],
(void*)(arr1 + 4));
printf("matrix[1] points to %p (expected arr2[4]: %p)\n", (void*)matrix[1],
(void*)(arr2 + 4));
}
```
we get
```
1 2 3 4
5 6 7 8
After loop:
matrix[0] points to 0x16fad2688 (expected arr1[4]: 0x16fad2688)
matrix[1] points to 0x16fad2678 (expected arr2[4]: 0x16fad2678)
```
(see that `matrix[0]` and `matrix[1]` are pointing out of bounds, which means that one could not reuse these pointers if one wanted to print the elements of the arrays one more time).
With the new version of the code
```c
#include <stdio.h>
// matrix -> arr -> integers
// similar to 01.c but with arrays
int main() {
int arr1[] = {1, 2, 3, 4};
int arr2[] = {5, 6, 7, 8};
int* ptr1 = arr1;
int* ptr2 = arr2;
int* matrix[] = {ptr1, ptr2};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 4; j++) {
printf("%d ", *(matrix[i] + j));
}
printf("\n");
}
printf("\nAfter loop:\n");
printf("matrix[0] points to %p (expected arr1[0]: %p)\n", (void*)matrix[0],
(void*)(arr1));
printf("matrix[1] points to %p (expected arr2[0]: %p)\n", (void*)matrix[1],
(void*)(arr2));
}
```
we get
```
1 2 3 4
5 6 7 8
After loop:
matrix[0] points to 0x16dd5a678 (expected arr1[0]: 0x16dd5a678)
matrix[1] points to 0x16dd5a668 (expected arr2[0]: 0x16dd5a668)
```
So now, after the end of the loop, `matrix[0]` and `matrix[1]` still point to the first elements of `arr1` and `arr2` respectively, and are not out of bounds anymore.
合并状态:已合并 合并于 2025-07-01 关闭于 2025-07-01 0 条评论