Reputation: 9
I want to get the size of an array from return value of a function. This is the function:
const char* bukaKunci(){
if(mlx.readObjectTempC() >= tempMin){ // if temp is lower than minimum temp
digitalWrite(selenoid, HIGH);
delay(1000);
return "Kunci terbuka!";
}
else{
digitalWrite(selenoid, LOW);
delay(1000);
return "Pintu terkunci";
}
return 0;
}
But when I check the size with this line:
const char* msg = bukaKunci();
int msg_len = sizeof(msg);
Serial.println(msg);
Serial.println(msg_len);
It gives me output the size of msg is 2, like this:
Kunci terbuka!
2
Did I missing something?
Upvotes: 0
Views: 438
Reputation: 989
If you want to get the length of a C string pointed at by a char*
, you can use strlen()
. sizeof()
is used to get the size of a type. As msg
is a pointer, you will get the size of the pointer, not the length of the string it is pointing at.
char msg [100] = "bar";
Serial.println (strlen (msg))
Upvotes: 1
Reputation: 416
int msg_len = sizeof(msg);
the above line of your function is returning the size of the object of the pointer and via pointer you can not determine the size of the array . May be you should read about a array decay
.
Two possible solutions .
strlen(msg)
will solve your problem
Upvotes: 1