plz give me links or discuss on address calculation in 2d arrays.
i have little knowledge of calculating the address. can any one give some formula or something coz my professor gave it but i wasnt able to follow . i remember he was using terms like rowmajor, column major, lower base , upper base etc.
so if any one is having knowledge plz help as this topic is not even in the book that i am using ( the course book i mean).

Dani AI

Generated

A compact, practical follow-up to 's question (and to the pointers from and ). The replies already point to row-major layout and simple pointer arithmetic. The notes below give a general formula that covers arbitrary lower bounds, the column-major alternative, a short C example that computes an element address in bytes, and common pitfalls to watch for.

General mapping (2D)

  • Let B = base address in bytes, S = size of one element (bytes), R = number of rows, C = number of columns, i = row index, j = column index, Lr/Lc = lower bounds (0 for C).
  • Row-major: Address(A[i][j]) = B + (((i - Lr) * C) + (j - Lc)) * S
    • For 0-based C arrays this becomes B + (i*C + j) * S.
  • Column-major (Fortran/MATLAB): Address(A[i][j]) = B + (((j - Lc) * R) + (i - Lr)) * S

Byte-offset example in C (0-based indices)

int arr[3][4];
int i = 2, j = 1; /* 0-based */
size_t offset = (i * 4 + j) * sizeof arr[0][0];
int *p = (int*)((char*)arr + offset);
/* *p is the same as arr[i][j] */

Practical notes and pitfalls

  • Confirm layout before using formulas: C/C++ built-in arrays are row-major; some other languages are column-major. Mixing these assumptions causes swapped indices.
  • int a[R][C] is a contiguous block; int **a with per-row malloc is not contiguous and cannot be indexed the same way.
  • For dynamic contiguous storage, allocate one block (malloc(R*C*sizeof *buf)) and index with i*C + j.
  • Always use sizeof for element size and cast to char* when adding byte offsets.

This fills the missing pieces from earlier replies: the full mapping formulas, how to adapt for non-zero lower bounds, and how to avoid common allocation/indexing traps.

Recommended Answers

All 2 Replies

In C and C++, arrays are stored in memory by row. That is, all the columns of the first row appear first, then all the columns of the second row, etc. If you have an int array with 2 rows and 5 columns then the location of any given row can be caluculated by this formula

int *p = array + ((row_numer-1) * NumColumns)
int array[2][5];
// set a pointer at the beginning of row 2
int* ptr = (int*)array + (1*5);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.