+ 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; }

6th Jan 2020, 12:03 PM
Paolo De Nictolis
Paolo De Nictolis - avatar
5 Respuestas
+ 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
6th Jan 2020, 12:18 PM
你知道規則,我也是
你知道規則,我也是 - avatar
+ 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
6th Jan 2020, 2:17 PM
MO ELomari
MO ELomari - avatar
+ 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)
6th Jan 2020, 2:50 PM
Ipang
+ 1
int arr[] = {1, 2, 3}; int* ptr = arr; ptr ++; printf("%d", *ptr);
16th Oct 2021, 9:22 AM
Shilpa L
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
22nd Feb 2023, 6:24 AM
Jembere Guta
Jembere Guta - avatar