arrayscmemory-address

Addresses and arrays in C


What is the difference (or link) between:

When should I use one or the other, or are they equivalent?


Solution

  • For 1D arrays:

    1. Element address using pointers:

      • This approach uses pointer arithmetic to calculate the address of the i-th element.
      • The base address of the array (arr) is a pointer, and adding i to it gives you the address of the i-th element.
      • This is a more direct and efficient way to access elements in a 1D array.
    2. Element address = base address + element size * element number:

      • This approach calculates the address of the i-th element by taking the base address and adding the product of the element size and the element number (i).
      • This is a more explicit and verbose way to calculate the address, but it can be useful in some situations, such as when the element size is not fixed (e.g., in a struct array).

    For 2D arrays:

    1. Address using pointers: *(arr + i) + j:

      • This approach first calculates the address of the i-th row using pointer arithmetic (arr + i), and then adds the offset of the j-th column (+ j) to get the final address.
      • This is a more direct and efficient way to access elements in a 2D array.
    2. Element address = base address + element size * ((row number * total number of columns) + column number):

      • This approach calculates the address of the element by taking the base address and adding the product of the element size, the row number, the total number of columns, and the column number.
      • This is a more explicit and verbose way to calculate the address, but it can be useful in some situations, such as when the element size is not fixed (e.g., in a struct array).

    In general, the pointer-based approaches (arr + i and *(arr + i) + j) are more commonly used and efficient, as they directly leverage the underlying memory layout of the arrays. However, the explicit address calculation can be useful in certain scenarios, such as when working with variable-sized elements or when the array dimensions are not known at compile-time.