2-D array in C, address generation
How do addresses get generated in arrays in C, say how does a [x][y] get to a particular value, i know 开发者_StackOverflowits not that big a question but just about to actually start coding.
Well it is done depending on your data type of whose array you have considered.
Say for an Integer array, each value holds 4 bytes, thus a row X long will take 4X bytes.
Thus a 2-D matrix of X*Y will be of 4*X*Y Bytes.
Any address say Arry[X][Y] would be calculated as : (Base Address of Arry) + (X * No. of columns) + ( Y // Offset in current row )
2-dimensional arrays in C are rectangular. For example:
int matrix[2][3];
allocates a single block of memory 2*3*sizeof(int)
bytes in size. Addressing matrix[0][1]
is just a matter of adding 0 * (3 * sizeof(int))
to sizeof(int)
. Then add that sum to the address at which matrix
starts.
A nested array is an array of arrays.
For example, an int[][6]
is an array of int[6]
.
Assuming a 4-byte int
, each element in the outer array is 6 * 4
= 24 bytes wide.
Therefore, arr[4]
gets the third array in the outer array, or *(arr + 4 * 24)
.
arr[4]
is a normal int[]
. arr[4][2]
gets the second int
in this inner array, or *(arr + 4 * 24 + 2 * 4)
E.g.
char anArray[][13]={"Hello World!","February","John"};
You can visualize it as:
anArray
:
H|e|l|l|o| |W|o|r|l|d|!|\0|F|e|b|r|u|a|r|y|\0|\0|\0|\0|\0|J|o|h|n|\0|\0|\0|0|\0
^ ^ ^
0 13 26
精彩评论