Last active
October 15, 2024 08:06
-
-
Save dipamsen/d8ee478d6580e5c848d9a454b8a7e0ff to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
int main() | |
{ | |
int arr[5] = {1, 2, 3, 4, 5}; | |
arr; // int[5]; array | |
&arr; // int (*)[5]; pointer to an array (note that (int *)[5] would be an array of pointers) | |
&arr[0]; // int *; pointer to an int | |
*arr; // int; arr decays it to its initial pointer (&arr[0]) then dereferencing gives arr[0] | |
// when the array (arr) by itself is used anywhere (eg. arithmetic operation, passing into a function) | |
// it 'decays' into a pointer | |
// int[5] -> int * | |
// thus losing size information. | |
// It does not decay into a pointer, when: | |
// - it is used with & (&arr) | |
// - it is used with sizeof() | |
printf("%lu\n", sizeof(arr)); // 20 (5 * 4), when used with sizeof it doesnt decay and still means the entire array | |
printf("%lu\n", sizeof(&arr)); // 8, pointer's size | |
printf("%lu\n", sizeof(*arr)); // 4, int's size | |
// https://www.oreilly.com/library/view/understanding-and-using/9781449344535/ch04.html#PointersAndMultiDimensionArraysSection | |
// Incrementing behaviour: | |
arr + 1; // int * incremented by 1 * sizeof(int) &arr[1]; | |
&arr + 1; // int (*)[5] incremented by 1 * sizeof(int[5]) | |
// in general, (type *) variable on incrementing, has an offset of sizeof(type). | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment