sizeof a string

Hi all.

Yet again a question about the sizeof operator.
First an example of the code (without setup, loop etc.)

void function (char *_min, char *_max) (
  byte a = sizeof(_min);
  byte b = sizeof(_max);
  Serial.println(a, DEC);
  Serial.println(b, DEC);

function ("0", "36");    // first call
function ("-10, "36");    // second call

Desired effect;
That the first call prints

1  (size of 0)
2  (size of 36)

and the second call prints


This is what i do get;

2     //first call
2     // second call

Basically i don’t understand what the sizeof operator is evaluating. The strings will not change while running the program.

Hoping i explained my problem enough,


sizeof returns the size in bytes of the variable you give it, not the value associated with that variable. In the C language, a string variable is actually a pointer to the array of characters comprising the string. An arduino pointer is two byes, which is what sizeof correctly returns.

Use the strlen function to get the length of a string

Before i knew it i've learned something new. :)

Thanks a lot mem.


mem is right-- sizeof() measures the memory requirements for a type, not a specific value. And strings are the easiest way to get this confused, for a couple of reasons.

Try to predict, then actually run:

char* hello = "hello";
char as_an_array[20] = "hello";

int as_an_argument(char* arg)
    return sizeof(arg);

void setup()
    char* as_a_variable = hello;

    Serial.println(sizeof(hello), DEC);  // as an implied array
    Serial.println(sizeof("hello"), DEC);  // as a literal
    Serial.println(sizeof(hello[0]), DEC);  // as an array element
    Serial.println(sizeof(&hello[0]), DEC);  // as an explicit pointer
    Serial.println(as_a_variable(hello), DEC);
    Serial.println(as_an_argument(hello), DEC);
    Serial.println(sizeof(as_an_array), DEC);  // an explicit array
    Serial.println(strlen(hello), DEC);  // as a string

void loop() { ; }

If you're surprised by the difference in the first one and the last one, remember that a string like "hello" really has an extra char allocated for a 0 or NUL terminator. This isn't usually included in the string length, but is crucial to most uses in strings, so you have to keep that in mind.

Also, despite the appearance, sizeof() is not a function. It is an operator. The above example didn't make this obvious, but the compiler computes the answers to sizeof() before you even upload the program to the Arduino. What's the difference? The operator can take types directly, which you couldn't do with a function argument. Try adding Serial.println(sizeof(char), DEC) or Serial.println(sizeof(char*), DEC).