Declaration of String to size I want

Hi,
I would like to ask you if is possible to change string size in declaration. When I declare String mystring; and then I use Serial.println(sizeof(mystring)); Serial Monitor shows me 6. Is it possible to change the size of new String object for example to 4 bytes in declaration?

Thank you.

Is it possible to change the size of new String object for example to 4 bytes in declaration?

The sizeof() operator is NOT telling you how much data is in the String object. There are other methods for that. The sizeof() operator is telling you how much memory the String object uses, independent of the data that pointers it contains point to. Generally useless information.

If you want to force the string that the String points to to be a certain size, it almost certainly means that the String object is useless and that you should be using a string, instead.

I don't intend to explain the difference between a String and a string again.

In my (limited) understanding, the String object that you declare will be allocated more memory as and when required which is one of the reasons why some people do not like using String objects and prefer to use zero terminated arrays of chars, aka strings or C style strings.

nwinder:
Hi,
I would like to ask you if is possible to change string size in declaration. When I declare String mystring; and then I use Serial.println(sizeof(mystring)); Serial Monitor shows me 6. Is it possible to change the size of new String object for example to 4 bytes in declaration?

Thank you.

While it is generally regarded that use of the String class will cause problems, yes there is a way to Reserve a size of a String Object. I have never attempted to use it, though.

that said, you may be a lot better off just using C strings (aka null-terminated char arrays)

char myText[32] = "here is an example of a C string";

the null termination is done upon declaration, in this example.