Skip to content

Instantly share code, notes, and snippets.

@sharth
Last active May 17, 2021 11:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sharth/ede13c0502d5dd8d45bd to your computer and use it in GitHub Desktop.
Save sharth/ede13c0502d5dd8d45bd to your computer and use it in GitHub Desktop.
In C and C++:
Myth: Arrays are just pointers
Reality: Pointers are something else: Pointers do store a single address, while
arrays can store multiple values. Arrays are converted to pointers to their
first element implicitly and often.
I often see people write that arrays are just pointers pointing to a block of
memory. That yields to the fact that people try to pass arrays like if they
were pointers. Two dimensional arrays are tried to pass like
void myarray(int **array) { array[i][j]...; } // wrong! while believing if
they have two dimensions, they have a pointer to a pointer. In reality, an
array itself consists of the elements, it does not point to them:
int a[4][3]; sizeof(a) == 4 * sizeof(int[3]) There are many contexts in which
one needs to address a certain element of it. This is where it converts to a
pointer implicitly (i.e without programmers writing it). When passing the array
to a function, the function receives a pointer to the first element that points
to the array. That pointer is made up by the compiler as a temporary. The two
dimensional array of above, would thus be passed like this:
void myarray(int (*array)[3]); Which makes the parameter a pointer to the first
element of it, namely a pointer to the first 3-elements array.
@sharth
Copy link
Author

sharth commented Sep 6, 2013

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment