Display digital pin state as ON/OFF on and OLED display

As the title states I'm trying to get a digital pin state to display as on/off on a 1.3' OLED display. I currently have it displaying analog pin values as well as digital pin as 1 or 0.

I'm using this:

 int ac1 = digitalRead(inputac);
  sprintf(AC1,"%01d",ac1);

along with:

u8g2.drawStr(98,64,AC1);

and it displays fine.

What I'm attempting to use is this:

 buttonState = digitalRead(inputac);
  
  if (buttonState == HIGH) {
    char AC1[5]="on";
  } else {
    char AC1[5]="off";
  }

This may not be the correct way to do it and it certainly doesn't work. The first one I get a 1 or 0 when toggling the pin but with the second it displays nothing.

Any help would be appreciated. Thanks!

  sprintf(AC1,"%01d",ac1);

Does that really make sense? In a field width of 1, fill with leading zeros... Just how many leading 0s are you EVER going to have added?

This may not be the correct way to do it

It is not. The two variables named AC1 go out of scope IMMEDIATELY.

You need a global array or a static array at the proper scope. And, you need to populate the array correctly.

Or, you need a char pointer that you can make point to a different string literal.

Well that is the one that works fine even if it may not make sense. That is just modified from what I am using to display the output of the analog pins.

What I would like to do is fix the if else statement or find and alternative to it.

Paul told you - change the scope of AC1

 buttonState = digitalRead(inputac);
 char *AC1;

  if (buttonState == HIGH) {
    AC1="on";
  } else {
    AC1="off";
  }

Paul told you - change the scope of AC1

That's a little more than changing the scope. But, that is the simplest solution.