Counting Elements in an array passed to a function

For sizeof calculations in your function:
1.
str is a pointer to char.
sizeof(str) is the size of a pointer to char. (That's 2 for avr-gcc)
str[0] is a char
sizeof(str[0]) is the size of a char (That's always 1 in C and C++)

2.
&str is a pointer to pointer to char
sizeof(&str) is the size of a pointer to a pointer to char (That's 2 for avr-gcc)
str[0] is a char
&str[0] is a pointer to char
sizeof(&str[0]) is the size of a pointer to char (That's 2 for avr-gcc)

Next-to-bottom line: Inside the function whose parameter is a pointer, the function can not know the size of the array unless you tell it.

If the parameter is a pointer to char, with C-style "strings," you can tell the number of chars in the "string" with the strlen() function, but the function doesn't know whether the argument in the calling function was the address of a literal string (as it is in your program) or the address of the first element in an array or whatever. In particular, it doesn't know the size of the array.

In order for strlen() to work, you have to feed it the address of a sequence of chars that is terminated by a byte whose bits are all zero. The strlen() function starts counting at the address that you give it and stops when it sees the zero byte.

void setup()
{
    Serial.begin(9600);
}
void loop()
{
    char x[100];
    Serial.print("In main: sizeof(x)   = ");
    Serial.println(sizeof(x));
    
    foo(x);
    
    delay(10000);
}

// The function has no way (no way) of knowing the
// size of the array back in the calling function.
//
// It just prints out the size of a pointer to char.
//
void foo(char *bar)
{
    Serial.print("In foo:  sizeof(bar) =   ");
    Serial.println(sizeof(bar));
}

Output:


In main: sizeof(x)   = 100
In foo:  sizeof(bar) =   2

Bottom line: The compiler knows the size of the array when and where you declare it. When you pass the name of the array to a function, you are passing a pointer whose value is the address of the first element of the array. The pointer does not carry along any information as to the size of the array. Period. Full stop.

Regards,

Dave