Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access an element of an std::array given its pointer in C++

I'm trying to access an element of an std::array given its pointer in C++. Here's some code that illustrates my problem:

#include <iostream>
#include <array>

void func(std::array<int, 4> *);

int main()
{
    std::array<int, 4> arr = {1, 0, 5, 0};
    func(&arr);
}

void func(std::array<int, 4> *elements)
{
    for (int i = 0; i < 4; i = i + 1)
    {
        std::cout << *elements[i] << std::endl;
    }
}

I would expect this to print every element of the std::array on a new line. However, it doesn't even get past compiling:

main.cpp: In function ‘void func(std::array<int, 4ul>*)’:
main.cpp:16:22: error: no match for ‘operator*’ (operand type is ‘std::array<int, 4ul>’)
         std::cout << *elements[i] << std::endl;

What's going on here?
Thanks!

like image 201
QuantumFool Avatar asked Dec 18 '25 17:12

QuantumFool


1 Answers

Use

std::cout << (*elements)[i] << std::endl;

instead. Otherwise operator[] is applied first, as it has higher precedence, see http://en.cppreference.com/w/cpp/language/operator_precedence.

So you first need to dereference the pointer to get access to the first pointee, which is an array, then subsequently access the array with operator[]. Otherwise your code is parsed by the compiler as *(elements[i]), so first you get the i-th array (which of course is non-existent unless i==0), then you try to dereference it, hence the compile error.

Tip: If you're worried about copies, pass the array by const reference instead

void func(const std::array<int, 4>& elements)

Then your syntax inside the function will be "natural", i.e. elements[i] will simply denote the i-th element of the array reference elements. You'll also pass the array simply as func(arr);.

like image 176
vsoftco Avatar answered Dec 20 '25 07:12

vsoftco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!