TransWikia.com

Output is not shown in C

Stack Overflow Asked by cally on December 13, 2021

char DayName(int day_th)
{
  const char *DayName[] = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday" };
  return *DayName[day_th];
}

int main()
{
  int day_th=2;
  printf("What is your favorite day of the week? 1 is Sunday and 7 is Saturday: n");
  printf("Day %d is a %s", day_th, DayName(day_th-1));
  return 0;
}

I am writing a code that have output like "Day 2 is Monday". I am using VS 2019 and the compiler does not raise any errors. However, when I hit run, only "What is your favorite day … line" is shown but not the "Day 2 is Monday". Pleases help! Many thanks.

One Answer

You invoked undefined behavior by passing data having wrong type to printf: char is passed where char* is expected (%s).

The function DayName should return the elements of the array const char* without dereferencing them.

#include <stdio.h>

const char* DayName(int day_th)
{
  const char *DayName[] = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday" };
  return DayName[day_th];
}

int main()
{
  int day_th=2;
  printf("What is your favorite day of the week? 1 is Sunday and 7 is Saturday: n");
  printf("Day %d is a %s", day_th, DayName(day_th-1));
  return 0;
}

Answered by MikeCAT on December 13, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP