-
-
Save sharth/ede13c0502d5dd8d45bd 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
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. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a copy of: http://stackoverflow.com/questions/423823/whats-your-favorite-programmer-ignorance-pet-peeve/484900#484900 written by Johannes Schaub - litb