charArray sizeof different in main loop and a function

When I use sizeof(charArray) within the main loop of the program it works as expected. When I pass the charArray to a function, it cuts short.

The code I'm trying to get working:

char myStr[9] = "12345678";
int i;

void setup(){
    Serial.begin(115200);
    delay(1000);
    Serial.println("Starting");
}

void loop() { 
    uint8_t address = 0;
    Serial.print("now using main loop:");
    Serial.println(myStr);
    Serial.print("Sizeof in main loop:");
    Serial.println(sizeof(myStr) - 1);
    for (i = 0; i < sizeof(myStr) - 1; i++){
        Serial.print(i, DEC);
        Serial.print(" = ");
        Serial.write(myStr[i]);
        Serial.println();
    }
    address = writeCharArray(address, myStr);
    Serial.print("Next address:");
    Serial.println(address);
    delay(15000); // slow down the program
}

// uint8_t writeCharArray(uint8_t address, char charArray[]) { // get same result with this too
uint8_t writeCharArray(uint8_t address, char* charArray) {
    uint8_t nextAddress = address;
    Serial.print("now using function:");
    Serial.println(charArray);
    Serial.print("Sizeof in function:");
    Serial.println(sizeof(charArray) - 1);
    for (i = 0; i < sizeof(charArray) - 1; i++) {
        Serial.print(i, DEC);
        Serial.print(" = ");
        Serial.write(charArray[i]);
        Serial.println();
        nextAddress++;
    }
    return nextAddress;
}

The result I get:

now using main loop:12345678
Sizeof in main loop:8
0 = 1
1 = 2
2 = 3
3 = 4
4 = 5
5 = 6
6 = 7
7 = 8
now using function:12345678
Sizeof in function:3
0 = 1
1 = 2
2 = 3
Next address:3

I'm suspecting it's something to do with the passing of the charArray to the function that seems to cut it short, but it prints the full string when asked.

I'm using Adafruit HUZZAH ESP8266 @160MHz (not sure if that makes a difference)

Any guidance would be greatly appreciated.

Ok just figured out the problem. Can't get sizeof in the function because what's being sent is a pointer so the system will measure the sizeof the pointer, not what is being pointed to.

Solution:
Call the function using:

address = writeCharArray(address, myStr, sizeof(myStr));

And change the function to:

uint8_t writeCharArray(uint8_t address, char* charArray, int sizeOfArray) {
    uint8_t nextAddress = address;
    Serial.print("now using function:");
    Serial.println(charArray);
    Serial.print("Sizeof in function:");
    Serial.println(sizeof(charArray) - 1);
    for (i = 0; i < sizeOfArray - 1; i++) {
        Serial.print(i, DEC);
        Serial.print(" = ");
        Serial.write(charArray[i]);
        Serial.println();
        nextAddress++;
    }
    return nextAddress;
}

Well done :slight_smile:

Note that you can still use strlen() in a function. It's not the same thing because it tells you the number of characters in the string, not the size of the array.