Last active
August 29, 2015 14:04
-
-
Save jepio/399769aaac6572ded9b1 to your computer and use it in GitHub Desktop.
2D arrays in C (I always forget this)
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
// Static | |
int arr[3][5] = {0}; | |
printf("%d\n", arr[2][4]); | |
// Dynamic noncontiguous | |
int i; | |
int **arr = (int **) malloc(sizeof(int*)*3); | |
for ( i = 0 ; i < 3 ; ++i ) | |
arr[i] = (int *) malloc(sizeof(int)*5); | |
arr[2][4] = 0; | |
printf("%d\n", arr[2][4]); | |
// Dynamic contiguous (but actually 1D) | |
int *arr = (int *) malloc(sizeof(int)*3*5); | |
arr[2*5 + 4] = 0; | |
printf("%d\n", arr[2*5 + 4]); | |
// Dynamic contiguous with proper indexing | |
int (*arr)[5] = (int (*)[5]) malloc(sizeof(int)*3*5); | |
arr[2][4] = 0; | |
printf("%d\n", arr[2][4]); | |
// Dynamic contiguous differently | |
int i; | |
int **arr = (int **) malloc(sizeof(int*)*3); | |
int *temp = (int *) malloc(sizeof(int)*3*5); | |
for ( i = 0 ; i < 3 ; ++i ) | |
arr[i] = &temp[i*5]; // watch out for operator precedence | |
printf("%d\n", arr[2][4]); |
Casting the pointer type with malloc
is not necessary in C, mandatory in C++. However in C++ new
is the preferred way to allocate memory.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This compiles alright if the names of the variables are changed to remove redefinitions.