Concept
How can pointer manipulation create a contiguous two-dimensional array?
ComputerScienceOne / Contiguous 2-D Arrays
"In the following example, we will create a 4 × 3 sized matrix.\n\n1 int **m = (int **) malloc(sizeof(int *) * 4);\n\n2 m[0] = (int *) malloc(sizeof(int) * (4 * 3));\n\nWe’re not done yet, however. We still need to initialize all of the other pointers. To do so, we dereference the array (once) to get the address of the start of the memory block and then compute an offset from this beginning on where the next “row” should be. Since each row has 3 elements, this arithmetic is simple.\n\n1 for(i=1; i<4; i++) {\n\n2 arr[i] = (*arr + (3 * i));\n\n3 }\n\nNow we can treat the array like we would any other two dimensional array by specifying two indices.\n\n1 for(i=0; i<4; i++) {\n\n2 for(j=0; j<3; j++) {\n\n3 arr[i][j] = 10 * i + j;\n\n4 }\n\n5 }\n\nWhich would result in an array that, conceptually, looks something like the following.\n\n[ 0 1 2 ]\n\n[ 10 11 12 ]\n\n[ 20 21 22 ]\n\n[ 30 31 32 ]\n\nWhich are all stored in one large chunk of memory. To see this, we can print out the memory address of each “row” during a particular run of the program: arr[0] = 0x7fe51b403270 arr[1] = 0x7fe51b40327c arr[2] = 0x7fe51b403288 arr[3] = 0x7fe51b403294 Note that each hexadecimal value differs by 0x0c (that is, 12 bytes): 0x...70 + 0x0c = 0x...7c 0x...7c + 0x0c = 0x...88 0x...88 + 0x0c = 0x...94 This is exactly how many bytes the 3 integers (4 bytes each) take in memory in each “row.” The pointer setup is depicted in Figure"
Related Ideas
- How can you combine contiguous structure storage with indirect access?ComputerScienceOne · Arrays of Structures
- How can an array of structure pointers make swapping structures more efficient?ComputerScienceOne · Arrays of Structures
- How can you create an array of strings in C?ComputerScienceOne · Arrays of Strings
- How can pointer arithmetic and comparators implement a generic getMax()?ComputerScienceOne · Function Pointers
- How does malloc() allocate memory for a dynamic array?ComputerScienceOne · Dynamic Memory
- How do you use and validate a dynamically allocated array?ComputerScienceOne · Dynamic Memory
- How do you access array elements safely in C?ComputerScienceOne · Basic Usage
- What other memory allocation functions and pointer cast options does C provide?ComputerScienceOne · Dynamic Memory