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


i'm trying access element of std::array given pointer in c++. here's code illustrates 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) {     (int = 0; < 4; = + 1)     {         std::cout << *elements[i] << std::endl;     } } 

i expect print every element of std::array on new line. however, doesn't past compiling:

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

what's going on here?
thanks!

use

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

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

so first need dereference pointer access first pointee, array, subsequently access array operator[]. otherwise code parsed compiler *(elements[i]), first i-th array (which of course non-existent unless i==0), try dereference it, hence compile error.

tip: if you're worried copies, pass array const reference instead

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

then syntax inside function "natural", i.e. elements[i] denote i-th element of array reference elements. you'll pass array func(arr);.


Comments

Popular posts from this blog

node.js - Using Node without global install -

How to access a php class file from PHPFox framework into javascript code written in simple HTML file? -

java - Null response to php query in android, even though php works properly -