4

I was coding a class for "a kind of gun". I have this code for the classes:
Gun.h:

#ifndef Gun_h
#define Gun_h

#include "Arduino.h"

class Gun
{
  public:
    Gun(String identifier, String name, int teamIRCodes[]);
    String getIdentifier();
    String getName();
    int getIRCode();
  private:
    String _identifier;
    String _name;
    int _teamIRCodes[];
};

#endif

Gun.cpp:

#include "Arduino.h"
#include "Gun.h"

Gun::Gun(String identifier, String name, int teamIRCodes[])
{
  _identifier = identifier;
  _name = name;
  _teamIRCodes = teamIRCodes;
}

String Gun::getIdentifier(){
  return _identifier;
}
String Gun::getName(){
  return _name;
}
int Gun::getIRCode(){
  return _teamIRCodes[1];
}

It returns me this error while compiling:

sketch\Gun.cpp: In constructor 'Gun::Gun(String, String, int*)':

Gun.cpp:8: error: incompatible types in assignment of 'int*' to 'int [0]'

   _teamIRCodes = teamIRCodes;

                ^

exit status 1
incompatible types in assignment of 'int*' to 'int [0]'
Arnyminer Z
  • 197
  • 1
  • 2
  • 8

2 Answers2

1

The issue is with flexible array int _teamIRCodes[]; This is an old technique which I don't recommend. But if you want to use it, you need you use malloc to create a class object, adding on enough space for the array:

// Allocate space for the class AND the array
Gun *gun = (Gun *)malloc(sizeof(Gun) + sizeof(teamIRCodes));

However, this does not call the ctor, and you still have to manually copy the data:

for(int i = 0; i < (sizeof(teamIRCodes) / sizeof(teamIRCodes[0])); i++) {
    gun->_teamIRCodes[i] = teamIRCodes[i];
}

I think it's much simpler to use a pointer:

int* _teamIRCodes;

Then you can make your ctor:

Gun(String identifier, String name, int teamIRCodes[], int numberOfCodes) {
    _teamIRCodes = new int[numberOfCodes];
    // memcpy does the same thing as the for loop - copies the array
    memcpy(_teamIRCodes, teamIRCodes, sizeof(teamIRCodes[0]) * numberOfCodes);
}

And don' forget to add a dtor:

~Gun() {
    delete [] _teamIRCodes;
}

Or, if teamIRCodes is persistent throughout the lifetime of the object, you can just use a pointer to it:

 class Gun {
     public:
     int *_teamIRCodes;
     int _numberOfCodes;
     Gun(String identifier, String name, int teamIRCodes[], int numberOfCodes) {
         _teamIRCodes = teamIRCodes;
         _numberOfCodes = numberOfCodes;
   };

(Maybe this is an Arduino thing as this is the 2nd flexible array question I've seen today).

001
  • 963
  • 6
  • 11
0

Ok, using this worked:
Replace

_teamIRCodes = teamIRCodes;

For

for(int i = 0; i < (sizeof(teamIRCodes)/sizeof(int)) ;i++)
    _teamIRCodes[i] = teamIRCodes[i];

Needed to iterate through array, cannot copy full array.

Arnyminer Z
  • 197
  • 1
  • 2
  • 8