1,105,328 Community Members

calculating an address of an array element

Member Avatar
abdullateef
Newbie Poster
3 posts since Dec 2006
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

hi everyone

I wanna to ask about calculation of 2-D array address I remember that equation that can do this

for an array, char a[R][C];

Address of an element a[N][M]; = baseAddress + elementSize * (N*C+ M);

Is it right?? :)

Other thing, is it deferent if the array is lower or upper triangular, or the same way by substituting missing elements by zeros??
e.g.

1 15 20
3 30
60

Any help I would appreciate ..

thanks:)

Member Avatar
Narue
Bad Cop
12,139 posts since Sep 2004
Reputation Points: 5,693 [?]
Q&As Helped to Solve: 1,537 [?]
Skill Endorsements: 81 [?]
Team Colleague
 
0
 

>Is it right??
In theory. In practice it's more like this:

*( *( baseAddress + N ) + M )

Why? Because a two dimensional array isn't required to be strictly contiguous in memory. Pick any teacher and they'll tell you that the storage for a two dimensional array is just a one dimensional array that uses special subscripting rules like the one you posted. And that's true, to a point. The elements of an array are required to be contiguous, but at the boundaries of a one dimensional array, all bets are off.

It's because of this boundary rule that you can't portably treat a multidimensional array as a single dimensional array and use a mathematical formula to index it. So while the N*C+M example helps one to understand how multidimensional arrays work, it's not something you should be using in your code.

>Other thing, is it deferent if the array is lower or upper triangular, or
>the same way by substituting missing elements by zeros??
An array is an array. How you use the indices to represent your data doesn't change that.

You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article