C++ / Arduino: dynamic int array - c++

I'm writing a class for the Arduino. It's been going well so far, but I'm sort of stuck now...
I have declared an int array in my class
class myClass
{
public: MyClass(int size);
private:
int _intArray[];
};
When I initialize the class MyClass myClass1(5) I need the array to look like this {0,0,0,0,0}.
My question: what do I need to do so that the array contains 'size' amount of zeros?
MyClass::MyClass(int size)
{
//what goes here to dynamically initialize the array
for(int i=0; i < size; i++) _intArray[i] = 0;
}
Edit: Following up on various replies below, Arduino does not include the standard library so unfortunately std::vector is not an option

Your code as I'm writing this:
class myClass
{
public: MyClass(int size);
private:
int _intArray[];
};
The declaration of _intArray is not valid C++: a raw array needs to have a size specified at compile time.
You can instead instead use a std::vector:
class myClass
{
public:
MyClass( int size )
: intArray_( size ) // Vector of given size with zero-valued elements.
{}
private:
std::vector<int> intArray_;
};
Note 1: some compilers may allow your original code as a language extension, in order to support the "struct hack" (that's a C technique that's not necessary in C++).
Note 2: I've changed the name of your member. Generally underscores at the start of names can be problematic because they may conflict with names from the C++ implementation.
Cheers & hth.,

You should use a std::vector.
class myCLass {
public:
myClass(int size)
: intarray(size) {
for(int i = 0; i < size; i++) intarray[i] = 0;
}
private:
std::vector<int> intarray;
};

You should really use vectors as others have suggested. A work-around could be as shown (in case you do not want to use memcpy or a loop).
This would be useful if you have a really huge array. Note that it would add a level of indirection to access the array.
class myClass
{
public:
myClass(){
mt = T(); // value initialize.
}
private:
struct T{
int _intArray[10];
} mt;
};
int main(){
myClass m;
}

I'll try the following:
class myClass
{
public:
MyClass(int size);
~MyClass();
private:
int* _intArray;
};
MyClass::MyClass(int size) {
_intArray = new int[size];
for (int i=0; i<size; ++i) _intArray[i] =0; // or use memset ...
}
MyClass::~MyClass() {
delete[] _intArray;
}
Or, even better, use a STL vector instead ...

you can use another hack basing on a string value and then populate a limited size array
check this :
https://github.com/Riadam/ViewPort-Array-Shifter-for-Arduino-Uno.git

Related

Create a heap-based 2D array without using double pointer syntax?

I need to declare a 2D array as the member variable of a class. I can't use STL (so, no vector), and I've been asked to avoid double/triple pointers. I want to be able to reference elements in this 2D array using subscripting notation, e.g. arr[0][0]. The array also must be declared on the heap due to its size.
Due to the requirements I have, none of the existing answers on StackOverflow meet my needs.
What I've been trying to do is:
class MyClass {
public:
MyClass() : arr(new int[1000][2]) {}
// other stuff here
private:
int arr[1000][2];
};
The error I get after compiling that class is "cannot initialize a parameter of type int * with an lvalue of type int[1000][2]". Clearly, I can solve this by using pointer syntax, but, as mentioned above, I've been asked to use "array syntax" for code clarity. I was hoping someone with a better understanding of C++ could explain how to use "array syntax".
Of course you can do this without double/triple pointers. You can even do this without use of any pointers in the class declaration. But first lets look at the more common approach. A 2D array is a simple extension of a 1D array.
Starting off with the standard way this is done for a 1D array of 1000 ints w/o using vector. The pointer, arr, is on the stack but points to an array of 1000 ints on the heap.
class MyClass {
public:
MyClass() : arr(new int[1000]) {}
private:
int *arr;
};
Elements are accessed the usual way. For instance arr[0]=42;
Extending this to a 2D array in the heap is a simple extension of the above.
You need to declare the member variable as a pointer to a 1D array instead of the basic type.
class MyClass {
public:
MyClass() : arr(new int[1000][2]) {}
private:
int (*arr)[2];
};
Similarly, you can refer to elements of the 2D array the usual way: arr[0][0]=42;
Finally, there is the approach that completely eliminates pointers except the one required for the new. Here we initialize a reference. The trick is to add a third level to new, the [1] so that the *new returns an object that is the actual 2D int array. Structurally, it is no different than what the pointer version above does but lets us directly initialize a reference to a 2D int array. It's certainly not a common idiom so I'd stick with the ptr approach.
class MyClass {
public:
MyClass() : arr(*new int[1][1000][2]) {}
~MyClass() {delete[] arr;}
//private: // to test
int(&arr)[1000][2];
};
int main()
{
MyClass obj;
obj.arr[2][1] = 42;
}
When your class has an array in it, and you use new to create a new instance of that class, that array is on the heap. You can still access the array with arr[i][j].
Why not do something like this?
class myClass {
public:
int arr[1000][2];
};
int main() {
myClass* test = new myClass;
for (int i = 0; i < 1000; i++) {
for (int j = 0; j < 2; j++) {
test->arr[i][j] = 5;
}
}
}
You can use 2 classes to achieve this.
class BaseArray {
public:
int& operator[](int x) { return this->arr[x]; }
int operator[](int index) const { return this->arr[index]; }
int arr[2];
};
class myClass {
public:
myClass() {}
~myClass() {}
BaseArray& operator[](int index) { return this->arr[index]; }
BaseArray operator[](int index) const { return this->arr[index]; }
BaseArray arr[1000];
};
Optionally use can use templates to make this class more dynamic.
template<class TYPE, int arraySize>
class BaseArray {
public:
TYPE& operator[](int x) { return this->arr[x]; }
TYPE operator[](int index) const { return this->arr[index]; }
TYPE arr[arraySize];
};
template<class TYPE, int dim1, int dim2>
class myClass {
public:
myClass() {}
~myClass() {}
BaseArray<TYPE, dim2>& operator[](int index) { return this->arr[index]; }
BaseArray<TYPE, dim2> operator[](int index) const { return this->arr[index]; }
BaseArray<TYPE, dim2> arr[dim1];
};
int main()
{
myClass<int, 1000, 2> myArray;
}
EDIT
When you provide the array dimentions int arr[1000][2]; the variable will automatically be allocated in the stack. If the array needs to be fully dynamic, you can just use a double pointer int** arr = { nullptr }; and initialize it at the constructor as shown below.
class myClass {
public:
myClass()
{
arr = new int* [1000];
for (int i = 0; i < 1000; ++i)
arr[i] = new int[2];
}
~myClass()
{
/* Make sure to delete or else it might flag a memory error. */
for (int i = 0; i < 1000; ++i)
delete[] arr[i];
delete[] arr;
}
int** arr = { nullptr };
};

Initializing a vector on a class constructor

I'm doing this A class which has a vector of B's. I'm initializing the vector on the constructor of the A class (I'm not sure if this is the right way, but it compiles). Besides this, I'm having a problem because I don't want that when initializing the vector that it initializes himself with the default construtor of B() because this makes me do a for loop to set the value that I want. It would be fine if the vector position stood NULL or stood 0 to size;
class B{
int _t;
public:
B(){ _t = 1; }
B(int t) : _t(t){}
};
class A{
std::vector<B> _b;
public:
A(int size): _b(size){
for(int i = 0; i < size; i++){
_b[i].setNumber(i);
}
};
int main() {
int n = 3;
A _a(n);
return 0;
}
You can simply let the vector be default constructed (empty), then emplace_back into it:
A(int size) {
_b.reserve(size);
for(int i = 0; i < size; i++){
_b.emplace_back(i);
}
}
If you are stuck with a pre-C++11 compiler, you can push_back B objects into it:
A(int size) {
_b.reserve(size);
for(int i = 0; i < size; i++){
_b.push_back(B(i));
}
}
The calls to std::vector::reserve are to avoid re-allocations as the vector grows in size.
It does not compile. class B does not have a setNumber function. Initializing the vector to a size does not require you to do anything. It would just default construct number of objects equal to the specified size. Vector has a reserve member function that allows you to allocate enough memory for some number of elements without actually constructing objects. Perhaps that is what you were seeking. Obviously leaving it empty until you are ready to perform some form of insertion is another option. Hopefully one or more of the posted answers will help.
class A{
std::vector<B> _b;
public:
A(int size){
_b.reserve(size);
}
};

Is it possible to initialize a private array in a header file with a member which is initialized in the constructor? c++

I would like to declare an array in a header file but I would like have the size of the array declared when the class is constructed. Is this possible? I found a lot of array declarations on this site but not this in particular. When I try the code below I get the error "array bound is not an integer constant before ']' token"
foo.h
class foo{
private:
uint16_t _size;
uint16_t array[_size];
public:
foo(uint16_t size);
virtual ~foo();
}
foo.cpp
#include "foo.h"
foo::foo(uint16_t size)
:_size(size)
{
}
One particular way of doing it is this
class foo
{
public:
foo(uint16_t size);
private:
uint16_t _size;
uint16_t* array;
};
foo::foo(uint16_t size) :_size(size)
{
array = new int[_size];
}
That will allow you to dynamically create an array at runtime, I would suggest you use a std::vector though because generally they are a lot better than arrays in C++(IMO) but if you have a particular reason to use an array thats the way I'd do it. Using static means that if you wanted to use that class elsewhere then _size would share the same values between instances also I wouldn't think that would compile because only static functions can access static members.
EDT: in my haste to answer I forgot to say that you should add a destructor in your class to destroy the array when the class goes out of scope something like this
foo:~foo()
{
delete[] array;
}
Got downvoted because I never added in a reference to rule of three. Ideally you shouldn't use dynamically initialised arrays anyway and just use vectors here's the link to the rule of three C++ rule of three
Ideally, you should use std::vector<uint16_t>: it lets you decide the size dynamically, like this:
vector<uint16_t> array;
...
foo(size_t size) : array(size) {}
...
Alternatively, you can use a pointer instead of the array, allocate it in the constructor, and delete in the destructor:
uint16_t *array;
...
foo(size_t size) : array(new uint16_t[size]) {}
...
~foo() {delete[] array;}
This is not as good, because once you define the destructor, you need to deal with the rule of three.
You could use template parameter to define array size, if you really have to use array:
template<size_t N>
class foo{
private:
uint16_t array[N];
public:
foo()
{
}
};
foo<3> f;
std::vector is dynamic array in C++, it provides rich interfaces to operate array, there is little reason not to use std::vector.
class foo{
private:
    std::vector<uint16_t> array;
  
public:
    foo(uint16_t size) : array(size)
    {
    }
};
You can't do that. The size of an array must be a compile time constant. In your case the size of an instance of class foo depends on the size of the array. If you know the size of the contained array at compile time for every use of class foo, then you could use a template:
template <size_t N>
class foo {
uint16_t array[N];
public:
foo() {}
};
Otherwise you should use the resizable array offered by C++: std::vector:
class foo {
std::size_t size;
std::vector<uint16_t> array;
public:
foo(std::size_t size_)
: size(size_)
, array(size_)
{}
};
Use a vector.
class foo{
private:
std::vector<uint16_t> array;
public:
foo(uint16_t size)
};
foo::foo(uint16_t size) : array(size)
{
}
That's not how you initialize a static variable. Here's how (usually in the CPP file):
uint16_t foo::_size = /* something */;
But I don't think you want a static variable.
I'd suggest you to go with dynamic allocated arrays instead:
class foo{
private:
uint16_t _size;
uint16_t* array;
static uint16_t* copy(uint16_t* a, uint16_t s) {
if (!a) return 0;
uint16_t* ret = new uint16_t[s];
for (int i = 0; i < s; i++) ret[i] = a[i];
return ret;
}
public:
foo(const foo& f) : _size(f._size), array(0) { array = copy(f.array, f._size); }
foo(uint16_t size = 0) : _size(size), array(0) {
if (size == 0) return;
array = new uint16_t[_size];
}
~foo() { delete[] array; }
}
Even a better solution would be to use one of the standard library containers such as std::vector.

C++ initialize all values of a member array for a class

In C++ how initialize all values of a member array for a class?
#define MAX_MATRIX 20
Class Matrix {
public:
Matrix(); //constructor
protected:
int n[MAX_MATRIX]; // note cannot do = { 0} or w/e here
};
Matrix::Matrix()
{
// how to set all n to -1?
}
You can use std::fill:
std::fill(begin(n), end(n), -1);
(These begin and end functions can be found in namespace std in C++11, or you can easily implement them yourself in C++03)
This was a glaring shortcoming of C++03. In C++11 this has been fixed, and you can now initialize everything, including arrays:
class Matrix
{
public:
Matrix() : n { } { }
protected:
static const unsigned int MAX_MATRIX = 20;
int n[MAX_MATRIX];
};
(The nasty preprocessor macro is also not needed in C++.)
In C++03, you simply cannot initialize an array member, but you can set it to something meaningful in the constructor body, e.g. via std::fill(n, n + MAX_MATRIX, 0);.
(Of course it would be a lot nicer to say std::array<int, MAX_MATRIX> n;.)
There's a type for this:
class Matrix {
public:
Matrix() : n() { n.fill(-1); }
protected:
std::array<int, 20> n;
};
for (unsigned i = 0; i < MAX_MATRIX; ++i) n[i] = -1;
#include <cstring>
...
Matrix::Matrix()
{
static bool init=false;
static int n_init[MAX_MATRIX];
if (!init){
for(int i=0; i<MAX_MATRIX; i++){
n_init[i] = -1;
}
init = true;
}
memcpy(n,n_init,MAX_MATRIX*sizeof(int));
}
The array n_init is initialized exactly once and stored in memory, then all subsequent constructions are a quick memory copy with no loops. You should not see much decrease in speed if you increase the size of MAX_MATRIX as you would when looping through the index, particularly if you are calling Matrix::Matrix() many times.

initialize a const array in a class initializer in C++

I have the following class in C++:
class a {
const int b[2];
// other stuff follows
// and here's the constructor
a(void);
}
The question is, how do I initialize b in the initialization list, given that I can't initialize it inside the body of the function of the constructor, because b is const?
This doesn't work:
a::a(void) :
b([2,3])
{
// other initialization stuff
}
Edit: The case in point is when I can have different values for b for different instances, but the values are known to be constant for the lifetime of the instance.
With C++11 the answer to this question has now changed and you can in fact do:
struct a {
const int b[2];
// other bits follow
// and here's the constructor
a();
};
a::a() :
b{2,3}
{
// other constructor work
}
int main() {
a a;
}
Like the others said, ISO C++ doesn't support that. But you can workaround it. Just use std::vector instead.
int* a = new int[N];
// fill a
class C {
const std::vector<int> v;
public:
C():v(a, a+N) {}
};
It is not possible in the current standard. I believe you'll be able to do this in C++0x using initializer lists (see A Brief Look at C++0x, by Bjarne Stroustrup, for more information about initializer lists and other nice C++0x features).
std::vector uses the heap. Geez, what a waste that would be just for the sake of a const sanity-check. The point of std::vector is dynamic growth at run-time, not any old syntax checking that should be done at compile-time. If you're not going to grow then create a class to wrap a normal array.
#include <stdio.h>
template <class Type, size_t MaxLength>
class ConstFixedSizeArrayFiller {
private:
size_t length;
public:
ConstFixedSizeArrayFiller() : length(0) {
}
virtual ~ConstFixedSizeArrayFiller() {
}
virtual void Fill(Type *array) = 0;
protected:
void add_element(Type *array, const Type & element)
{
if(length >= MaxLength) {
// todo: throw more appropriate out-of-bounds exception
throw 0;
}
array[length] = element;
length++;
}
};
template <class Type, size_t Length>
class ConstFixedSizeArray {
private:
Type array[Length];
public:
explicit ConstFixedSizeArray(
ConstFixedSizeArrayFiller<Type, Length> & filler
) {
filler.Fill(array);
}
const Type *Array() const {
return array;
}
size_t ArrayLength() const {
return Length;
}
};
class a {
private:
class b_filler : public ConstFixedSizeArrayFiller<int, 2> {
public:
virtual ~b_filler() {
}
virtual void Fill(int *array) {
add_element(array, 87);
add_element(array, 96);
}
};
const ConstFixedSizeArray<int, 2> b;
public:
a(void) : b(b_filler()) {
}
void print_items() {
size_t i;
for(i = 0; i < b.ArrayLength(); i++)
{
printf("%d\n", b.Array()[i]);
}
}
};
int main()
{
a x;
x.print_items();
return 0;
}
ConstFixedSizeArrayFiller and ConstFixedSizeArray are reusable.
The first allows run-time bounds checking while initializing the array (same as a vector might), which can later become const after this initialization.
The second allows the array to be allocated inside another object, which could be on the heap or simply the stack if that's where the object is. There's no waste of time allocating from the heap. It also performs compile-time const checking on the array.
b_filler is a tiny private class to provide the initialization values. The size of the array is checked at compile-time with the template arguments, so there's no chance of going out of bounds.
I'm sure there are more exotic ways to modify this. This is an initial stab. I think you can pretty much make up for any of the compiler's shortcoming with classes.
ISO standard C++ doesn't let you do this. If it did, the syntax would probably be:
a::a(void) :
b({2,3})
{
// other initialization stuff
}
Or something along those lines. From your question it actually sounds like what you want is a constant class (aka static) member that is the array. C++ does let you do this. Like so:
#include <iostream>
class A
{
public:
A();
static const int a[2];
};
const int A::a[2] = {0, 1};
A::A()
{
}
int main (int argc, char * const argv[])
{
std::cout << "A::a => " << A::a[0] << ", " << A::a[1] << "\n";
return 0;
}
The output being:
A::a => 0, 1
Now of course since this is a static class member it is the same for every instance of class A. If that is not what you want, ie you want each instance of A to have different element values in the array a then you're making the mistake of trying to make the array const to begin with. You should just be doing this:
#include <iostream>
class A
{
public:
A();
int a[2];
};
A::A()
{
a[0] = 9; // or some calculation
a[1] = 10; // or some calculation
}
int main (int argc, char * const argv[])
{
A v;
std::cout << "v.a => " << v.a[0] << ", " << v.a[1] << "\n";
return 0;
}
Where I've a constant array, it's always been done as static. If you can accept that, this code should compile and run.
#include <stdio.h>
#include <stdlib.h>
class a {
static const int b[2];
public:
a(void) {
for(int i = 0; i < 2; i++) {
printf("b[%d] = [%d]\n", i, b[i]);
}
}
};
const int a::b[2] = { 4, 2 };
int main(int argc, char **argv)
{
a foo;
return 0;
}
You can't do that from the initialization list,
Have a look at this:
http://www.cprogramming.com/tutorial/initialization-lists-c++.html
:)
A solution without using the heap with std::vector is to use boost::array, though you can't initialize array members directly in the constructor.
#include <boost/array.hpp>
const boost::array<int, 2> aa={ { 2, 3} };
class A {
const boost::array<int, 2> b;
A():b(aa){};
};
How about emulating a const array via an accessor function? It's non-static (as you requested), and it doesn't require stl or any other library:
class a {
int privateB[2];
public:
a(int b0,b1) { privateB[0]=b0; privateB[1]=b1; }
int b(const int idx) { return privateB[idx]; }
}
Because a::privateB is private, it is effectively constant outside a::, and you can access it similar to an array, e.g.
a aobj(2,3); // initialize "constant array" b[]
n = aobj.b(1); // read b[1] (write impossible from here)
If you are willing to use a pair of classes, you could additionally protect privateB from member functions. This could be done by inheriting a; but I think I prefer John Harrison's comp.lang.c++ post using a const class.
interestingly, in C# you have the keyword const that translates to C++'s static const, as opposed to readonly which can be only set at constructors and initializations, even by non-constants, ex:
readonly DateTime a = DateTime.Now;
I agree, if you have a const pre-defined array you might as well make it static.
At that point you can use this interesting syntax:
//in header file
class a{
static const int SIZE;
static const char array[][10];
};
//in cpp file:
const int a::SIZE = 5;
const char array[SIZE][10] = {"hello", "cruel","world","goodbye", "!"};
however, I did not find a way around the constant '10'. The reason is clear though, it needs it to know how to perform accessing to the array. A possible alternative is to use #define, but I dislike that method and I #undef at the end of the header, with a comment to edit there at CPP as well in case if a change.