1

If I had an array of size 10 with a base address of say 0x5600bc. What would be the memory location of each element of the array and of the ptr?

Ex: What is Arr[0] address, would it be 0x5600bc? & would that make Arr[1] be 0x5600c0?

Ziezi
  • 6,375
  • 3
  • 39
  • 49
kids
  • 57
  • 7

3 Answers3

4

Given

typename foo[10] = { 0 };

Then foo[0] will be at some address, (uintptr_t)&foo[0].

foo[1] is at (uintptr_t)&foo[0] + sizeof typename, and foo[n] is at (uintptr_t)&foo[0] + n * sizeof typename.

Like this (assuming a 4 byte type here)

0x00000000 arr[0] <- arr is a pointer to this location
0x00000004 arr[1]
0x00000008 arr[2]
...

If you have an array of 32-bit integers, that's 4 bytes each, and the array starts at 0x5600bc then yes, arr[1] will be at 0x5600c0.

You can print the addresses of each element in your array like so:

#include <stdlib.h>
#include <stdio.h>

int main(void) {
  #define ARR_SIZE 10
  int arr[ARR_SIZE] = {0};

  for (size_t n = 0; n < ARR_SIZE; ++n) {
    printf("arr[%zu] = %p\n", n, (void*)&arr[n]);
  }

  return EXIT_SUCCESS;
}
Iskar Jarak
  • 5,136
  • 4
  • 38
  • 60
2

The location of Arr[n] will be 0x5600bc + n*sizeof(Arr[0]). So if the size of the array elements is 4, Arr[1] will indeed be at 0x5600c0.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

Array name (identifier) is actually a pointer to its first element, so the answer to Arr[0] is 0x5600bc. Depending on the type of the array and more specifically its element size (in bytes) will determine the increment of the address of each next element.

In general, Indirect addressing mode is used, where you have: base address + offset, where base = array name, offset = (element size)*(index of element)

Great explanations for arrays and pointer and arrays.

Graphical representation: enter image description here

Ziezi
  • 6,375
  • 3
  • 39
  • 49