Pointer or reference to a whole array

closed account (EwCjE3v7)
Hello there, so I would like to know if you can make a pointer or reference to a whole array. I`m using the pointer or reference in a function and that needs to modify the the array that its pointing at or is a reference of
1
2
3
4
5
6
7
8
9
10
void f ( T (& arr)[ N ] ) // pass array by reference
{
    // ... access elements by arr[i]
}


void f ( T* arr, size_t size ) // pass by pointer
{
    // ... access elements by arr[i]
}


A std::array<> container also exists in C++11
http://www.cplusplus.com/reference/array/array/?kw=array
Last edited on
Yes of course you can, in fact if you use the variable name of an array without the element access operator then that behaves as a pointer to that array which is more or less how C-strings work.
What do you mean a whole array?
C style arrays such as int Foo[500]; essentially _are_ pointers (that is, Foo in this example is a pointer to the first element of a 500 long array of ints)
I`m using the pointer or reference in a function and that needs to modify the the array that its pointing at or is a reference of
So go ahead and modify it.
closed account (EwCjE3v7)
Thank you guys, got it working. Thank you for the help.
> I would like to know if you can make a pointer or reference to a whole array.

Yes. Pointer to array is different from pointer to first element of array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>

template < typename T, std::size_t N >
void foo( T (&reference_to_array)[N] ) // pass array by reference
{
    for( T& v : reference_to_array ) ++v ;
}

template < typename T, std::size_t N >
void bar( T (*pointer_to_array)[N] ) // pass pointer to array
{
    if( pointer_to_array != nullptr ) for( T& v : *pointer_to_array ) ++v ;
}


template < typename POINTER >
void baz( POINTER pointer_to_first_element[], std::size_t n ) // pass pointer to first element and size
{
    if( pointer_to_first_element != nullptr )
        for( std::size_t i = 0 ; i < n ; ++i ) ++pointer_to_first_element[i] ;
}

template < typename POINTER >
void foobar( POINTER begin, POINTER end ) // pass pair of iterators
{
    for( ; begin != end ; ++begin ) ++ *begin ;
}

int main()
{
    const std::size_t N = 5 ;
    int a[N] = { 0, 1, 2, 3, 4 } ;
    const auto print = [&a] { for( int v : a ) std::cout << v << ' ' ; std::cout << '\n' ; } ;

    print() ;

    foo(a) ; print() ;

    bar( &a ) ; print() ;

    baz( a, N ) ; print() ;

    foobar( a, a+N ) ; print() ;
}

http://coliru.stacked-crooked.com/a/a1564f2712d1420b
Topic archived. No new replies allowed.