0

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?

4
  • sizeof tells you the size of the pointer here, not the size of the array whose first element the pointer points to. In general, you cannot determine the size of an array given only a pointer to the first element. However, since you know the pointer always points to a null-terminated string here, you can use strlen to find the length of the string. Commented May 19, 2020 at 2:34
  • 1
    Yes. You missed three key facts. Firstly, a pointer is not an array. Second, it is possible to return a pointer but not (directly) to return an array from a function (nor is it possible (directly) to pass an array to a function, since only a pointer will be passed). Third, when sizeof is applied to a pointer, it gives the size of the pointer, regardless of whether that pointer points at (the first element of) an array. Commented May 19, 2020 at 2:35
  • @cigien Thanks, you guide me to the solution. Commented May 19, 2020 at 2:37
  • @BessieTheCow Yup, my bad. But thank you, your respond is also helpful. Commented May 19, 2020 at 2:39

2 Answers 2

1
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 .

  1. Iterate over the array with a counter and counter will tell you the exact size
  2. use built in function like
strlen(msg)

will solve your problem

Sign up to request clarification or add additional context in comments.

Comments

1

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))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.