1

I don't write a lot of C, so I'm always discovering things I only partly understand in the Arduino variety. One of these is how Serial.print handles char[].

Does Serial.print always require a null terminator? In the case of (say) Serial.print(88, DEC); is a null implied?

What happens in the following cases?

char buff[3] = "ABC"; // warned because no room for a null
Serial.print(buff); // will absence of a null cause overrun?
char buff[4] = "ABC"; // now there's a null
Serial.print(buff); // will the null character be sent too?

Any references appreciated.

asked Sep 2, 2017 at 14:50

2 Answers 2

2

When passing a char* you need to also pass some way of telling the function where it ends. In C that is usually the null terminator and that's all a null terminator is for. If that is missing then you get a buffer overrun.

The null terminator is not sent.

answered Sep 2, 2017 at 15:16
3

The "Serial" is a object/class and that makes it possible to have more than one function for Serial.print(). According to the type of the parameter the proper Serial.print() is selected.

This is the include file for the Serial.print(): Print.h
And these are the possibilities:

  • size_t print(const __FlashStringHelper *);
  • size_t print(const String &);
  • size_t print(const char[]);
  • size_t print(char);
  • size_t print(unsigned char, int = DEC);
  • size_t print(int, int = DEC);
  • size_t print(unsigned int, int = DEC);
  • size_t print(long, int = DEC);
  • size_t print(unsigned long, int = DEC);
  • size_t print(double, int = 2);
  • size_t print(const Printable&);

The reference for Serial.print() is short, but it explains pretty well that those different parameters are possible.

Your Serial.print(88, DEC); does not use a string of text, it uses the integer number 88.

As soon as a string of text is used, it should be zero-terminated.
The line char buff[3] = "ABC"; is indeed wrong, as you already wrote. That is one of the things of the 'c' language. The "ABC" gets a zero-terminater and that makes 4 bytes.

answered Sep 2, 2017 at 19:53

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.