Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning pointers to arrays in C++

Tags:

c++

I want to do something like this below:

int main() {
   int a[10];
   int *d = generateArrayOfSize(10) // This generates an array of size 10 on the heap
   a = d;
   print(a); // Prints the first 10 elements of array.
}

However above code gives compilation error (incompatible types in assignment of ‘int*’ to ‘int [10]’). What can I do to make the above code to work?

like image 367
Bourne Avatar asked Jul 28 '13 13:07

Bourne


2 Answers

Arrays are non-assignable and non-copyable, so you'd have to copy each element by hand (in a loop), or using std::copy.

like image 141
Lightness Races in Orbit Avatar answered Sep 21 '22 21:09

Lightness Races in Orbit


If you're using C++, then use C++ arrays rather than C style arrays and pointers. Here's an example

#include <array>
#include <iostream>

template<size_t N>
std::array<int, N> generateArrayOfSize(void)
{
    std::array<int, N> a;
    for (int n=0; n<N; ++n)
        a[n] = n;
    return a;
}

template<size_t N>
void print(std::array<int, N> const &a)
{
    for (auto num : a)
        std::cout << num << " ";
}

int main() {
   std::array<int, 10> a;
   std::array<int, 10> d = generateArrayOfSize<10>();
   a = d;
   print(a); // Prints the first 10 elements of array.
}

which outputs 0 1 2 3 4 5 6 7 8 9

like image 36
cdmh Avatar answered Sep 20 '22 21:09

cdmh