+ 2
C - Why does ptr points to first address "after" arr?
#include <stdio.h> int main() { int arr[3] = {40, 41, 42}; int* ptr = (int*)(&arr+1); printf("%d \n", *ptr); printf("%d %d", *(arr+1), *(ptr-1)); return 0; }
5 Respostas
+ 2
*Sorry for the grammars. I don't speak English well ;(*
Before looking into the array. Let's take a look at the elements of the array.
You may know that *(arr+1) == arr[1]. But why so? It's because arr+1 moves 4 bytes forward since an int is 4 bytes. This thing is called "Pointer Arithmetic". The same as the array. arr[3] is 12 bytes. When it is added by 1. It moves 12 bytes forward and located at the int after arr[2].
ptr is int*, which means every move is 4 bytes. So ptr-1 is &arr[2].
For proper explanation, hope this helps! https://www.tutorialspoint.com/cprogramming/c_pointer_arithmetic.htm
+ 2
basically, "&arr" is of type int (*)[3] "a pointer to an array of 3 ints".
and with pointer arithmetic, adding an integer N to a pointer to an element of an array with index K produces a pointer to an element of the same array, with index K+N. since â&arrâ is pointer to array of 3 ints, addition of 1 resulted in an address with increment of (assuming sizeof int is 4 bytes) 4 x 3 = 12 (we end up to the addr of the next array of 3 ints if there was one ) which is decayed to int* (a pointer to an integer), subtraction of 1 resulted in an address with decrement of 4.
+-----+-----+-----+-----+-----+-----+
| 40 | 41 | 42 | | |
+-----+-----+-----+-----+-----+-----+
^ ^ ^ ^
| | | |
| | | |
| | | |
&arr | ptr-1 &arr + 1 == ptr
^ |
| |
arr arr + 1
+ 1
Here's a little snippet to accompany Mohamed ELOmari's wonderful illustration đ
#include <stdio.h>
int main()
{
int arr[3] = { 40, 41, 42 };
for(size_t i = 0; i < 3; i++)
printf("arr[%lu] = %d address %p\n", i, arr[i], &arr[i]);
int *ptr = (int *)(&arr + 1);
printf("\n*(ptr) = %2d address %p\n", *ptr, ptr);
for(size_t i = 1; i <= 3; i++)
printf("*(ptr - %lu) = %d address %p\n", i, *(ptr - i), ptr - i);
return 0;
}
(Edited)
+ 1
int arr[] = {1, 2, 3};
int* ptr = arr;
ptr ++;
printf("%d", *ptr);
0
Type in a code to increase the pointer using the increment operator and output the stored value:
int arr[] = {1, 2, 3};
int* ptr = arr;
ptr
-
;
printf("%d",
--
);
Here the answer for the given blank space is ++ and *ptr