2

I have made a class called subjects and I have then made a subject called math. I am trying to set a classroom for math but it is giving me the error 'math' doesn't name a type.

Code for the class

class subject {
public:
  char subjectname[];
  char classroom[];

};

Code for the classroom and math

subject math;
math.classroom = "A1";

How can I set the classroom of math to A1?

3
class subject {
public:
  char subjectname[];
  char classroom[];

};

This creates a class subject which has two char arrays of unspecified size as its members. This will attempt to create an array of size 0 (see here). This is not what you want. You can e.g. statically allocate the space with a maximum number of characters beforehand and then strncpy() your new string inside the buffer.

This would look like

class subject {
public:
  char subjectname[32];  //32 bytes buffer
  char classroom[32];
};

And later

subject math;
strncpy(math.classroom, "A1", 31); //copy at max 31 bytes to not overwrite the NUL terminator
Serial.print("Classroom is: ");
Serial.println(math.classroom)

Or, just use the Arduino String class. For example

#include <Arduino.h>
class subject {
public:
  String subjectname;
  String classroom;
};

Then your first usage code can be used unmodified.

Example

#include <Arduino.h>

class subject {
public:
  String subjectname;
  String classroom;
};

void setup() {
    Serial.begin(115200);

    subject math;
    math.classroom = "A1";

    Serial.print("Classroom is: ");
    Serial.println(math.classroom);
}

void loop() { }
  • I tried using this code but it gives me the error 'math' does not name a type at the math.classroom line. #include <Arduino.h> class subject { public: String subjectname; String classroom; }; subject math; math.classroom = "A1"; – TechnicProblem Feb 9 at 16:51
  • @TechnicProblem I can compile pastebin.com/5hVgtTi7 just fine. Does that compile for you? – Maximilian Gerhardt Feb 9 at 16:57
  • Thank you. Didn't know I should've put some of the code in void setup(). Now it works. – TechnicProblem Feb 9 at 17:26
  • @TechnicProblem You can put global variables outside of function scopes but not assignments and operations on them. Those must be in functions. – Maximilian Gerhardt Feb 9 at 18:18
  • +1 for your excellent answer. FWIW, the String sketch's compile size is 3644 bytes, and the strncpy sketch is 2112 bytes. +100 for using a class in your sketch. The difference in compile size (using the strncpy sketch) VS the same strncpy sketch with all the added OOP code is 0 bytes. Using a class costs you nothing, and gives you a lot. It is unfortunate that there are 3 votes to close this question, stating it's off topic. According to this page: arduino.stackexchange.com/help/on-topic , "Specific questions about Arduino boards, code…" are "On Topic". – VE7JRO Feb 10 at 1:05

Not the answer you're looking for? Browse other questions tagged or ask your own question.