Skip to content

Instantly share code, notes, and snippets.

@jepio
Last active August 29, 2015 14:04
Show Gist options
  • Save jepio/399769aaac6572ded9b1 to your computer and use it in GitHub Desktop.
Save jepio/399769aaac6572ded9b1 to your computer and use it in GitHub Desktop.
2D arrays in C (I always forget this)
// 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]);
@jepio
Copy link
Author

jepio commented Jul 26, 2014

This compiles alright if the names of the variables are changed to remove redefinitions.

@jepio
Copy link
Author

jepio commented Jul 27, 2014

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