Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2-D array in C, address generation

Tags:

arrays

c

How do addresses get generated in arrays in C, say how does a [x][y] get to a particular value, i know its not that big a question but just about to actually start coding.

like image 306
Lagnesh Avatar asked Feb 15 '11 18:02

Lagnesh


2 Answers

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 )

like image 198
Kartikya Avatar answered Nov 04 '22 12:11

Kartikya


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.

like image 34
nmichaels Avatar answered Nov 04 '22 14:11

nmichaels