sizeof() utility problem

Hello,

I am having a problem with the sizeof() utility.
The reference gives this program as an example:

char myStr[] = "this is a test";
int i;

void setup(){
Serial.begin(9600);
}

void loop() {
for (i = 0; i < sizeof(myStr) - 1; i++){
Serial.print(i, DEC);
Serial.print(" = ");
Serial.println(myStr*, BYTE);*

  • }*
    }
    [/quote]
    This program works with no problem.
    My problem with this example is that myStr is a global variable. If I try to pass a variable to a function where I need to use sizeof(), as in:
    > int i;
    >
    > void setup(){
    > Serial.begin(9600);
    > }
    >
    > void printWord(char myStr[])
    > {
    > for (i = 0; i < sizeof(myStr) - 1; i++){
    > Serial.print(i, DEC);
    > Serial.print(" = ");
    > Serial.println(myStr*, BYTE);*
    > * }*
    >
    > }
    > void loop()
    > {
    > * char myStr[] = "this is a test";*
    > * printWord(myStr);*
    > }
    > [/quote]
    > It simply sends 't' (the first character) over and over.
    > How do I pass variables in such a way that sizeof still works?
    > for the record it works if I set the for loop to i<14, and it works if I declare myStr within printWord.

You want "strlen()" instead of sizeof. sizeof is a compile-time thing, and only works for pieces of data whose size is know at the time of compilation, rather than at runtime.

How do I pass variables in such a way that sizeof still works?

You can't. Variables do not contain any extra information to allow their size, type, etc. to be determined at run time. That's a fundamental limitation of C/C++ implementation.

The way to do what you want is to pass the size in addition to the string.

void printWord(char myStr[], int strLen)
{
 int i;
 for (i = 0; i < strLen - 1; i++){
   Serial.print(i, DEC);
   Serial.print(" = ");
   Serial.println(myStr[i], BYTE);
 }

The more common way of handling this is to exploit the fact that a string is usually "null-terminated", meaning that the last character of the string is followed by a byte with a zero value.

void printWord(char myStr[])
{
 int i;
 for (i = 0; myStr[i] != '\0'; i++){
   Serial.print(i, DEC);
   Serial.print(" = ");
   Serial.println(myStr[i], BYTE);
 }

As a side note, sizeof is not a utility. Although it is usually used in a manner that suggests it is a function, it is actually a compile time operator. No parentheses are required with sizeof although they are frequently used. For example, the following code is perfectly legal.

int x;
int y = sizeof x;

That usage suggests the actual nature of the sizeof operator.

Thanks for the replies, this is a very responsive forum!

strlen() works great.

Good ideas Don, I always forget that the second argument in a for loop can be any condition at all. Very useful.