Bifalgorithm post · Computer science one · Contiguous 2-D Arrays

How can pointer manipulation create a contiguous two-dimensional array?

How can pointer manipulation create a contiguous two-dimensional array? (Computer science one · Contiguous 2-D Arrays) — "In the following example, we will cre…

Ideas in this flowchart

  • Dynamic representation of a 4 × 3 matrix in one contiguous memory block
  • The matrix contains 4 rows and 3 integer elements per row
  • Allocate an array of 4 integer pointers for the rows
  • Allocate one memory block for 4 × 3 integers
  • Initialize the remaining row pointers
  • Set each row pointer using the starting address plus an offset of 3 × i
  • Access the matrix with two indices
  • Assign each element the value 10 × i + j
  • The conceptual matrix contains the rows [0 1 2], [10 11 12], [20 21 22], and [30 31 32]
  • All matrix elements are stored in one large contiguous memory block
  • Printing the row addresses shows increasing hexadecimal addresses
  • The address difference between consecutive rows is 0x0c, or 12 bytes
  • Each row occupies 3 integers × 4 bytes, which equals 12 bytes
Feed/

How can pointer manipulation create a contiguous two-dimensional array?

No cover

Channel

Computer science one

1 page

"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"

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.