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(_min);
  Serial.println(b, DEC);
  Serial.println(_max);
}

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

Desired effect;
That the first call prints

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

and the second call prints

3  
-10
2
36

This is what i do get;

2     //first call
0
2
36
2     // second call
-10
2
36

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,

Jeroen

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.

Jeroen

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.begin(9600);
    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).