0

How can I access the individual memory addresses of elements of a char array? There's almost certainly a misconception in my understanding of what is going on here but I can't figure out what it is.

#include <array>
std::array<char, 10> arr{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
for (int i=0; i<arr.size(); i++){
    cout << i << " " << &i << " " << arr[i] << " " << &arr[i] << " "  << endl;
    }

Produces:

0 0x92f8c0 0 0123456789��� 
1 0x92f8c0 1 123456789��� 
2 0x92f8c0 2 23456789��� 
3 0x92f8c0 3 3456789��� 
4 0x92f8c0 4 456789��� 
5 0x92f8c0 5 56789��� 
6 0x92f8c0 6 6789��� 
7 0x92f8c0 7 789��� 
8 0x92f8c0 8 89��� 
9 0x92f8c0 9 9��� 
CiaranWelsh
  • 7,014
  • 10
  • 53
  • 106
  • 1
    Make it `(void*)(&arr[i])`. You see, `&arr[i]` is of type `char*`, and the stream's `operator<<` has a special case for `char*`, interpreting it as a pointer to a nul-terminated string and printing that string. – Igor Tandetnik Dec 17 '19 at 15:48
  • 1
    TL;DR of the dupe: `static_cast(&arr[i])` – NathanOliver Dec 17 '19 at 15:48
  • 4
    `&arr[i]` is the correct way to access the address. What you're seeing is the `<<` operator's handling of `char*`. And if you had a null char at the end of your array you wouldn't see the �, because the standard `char*` handling expects zero-termination. – Brannon Dec 17 '19 at 15:49
  • Perfect, thanks for the explaination and pointer to the dupe question. – CiaranWelsh Dec 17 '19 at 15:57

0 Answers0