SHUBHAM TANDAN SHUBHAM TANDAN - 3 months ago 10
C Question

returning a string from a function in c with parameters 4

Please look the code below

#include<stdio.h>
char* day(int);
int main()
{
int num;
char *p;
printf("Enter the day \n");
scanf("%d",&num);
p=day(num);
printf("%s",*p);
return 0;
}

char *day(int num)
{
char *str;
switch(num)
{
case 1: *str="MONDAY";
break;
case 2: *str="TUESDAY";
break;
case 3: *str="WEDNESDAY";
break;
case 4: *str="THURSDAY";
break;
case 5: *str="FRIDAY";
break;
case 6: *str="SATURDAY";
break;
case 7: *str="SUNDAY";
break;
}
return str;
}


I'm trying to print the days in a week in the above program in order to achieve this I have created a function day() which will accept the number from the user and will return the address of day but the above program is not working .I don't know what is the problem.Can anyone help me to solve this problem?

Answer

Remove '*' from str in day function, as you are assigning contents through pointers

Go through Basic Pointer Operations for pointer fundamentals.

 #include<stdio.h>


  char* day(int);
  int main()
 { 
   int num;
   char *p;
  printf("Enter the day \n");
  scanf("%d",&num);
  p=day(5);
  printf("%s",p);
   return 0;
 }

  char* day(int num)
 {
  char* str;
   switch(num)
 {
   case 1: str="MONDAY";
           break;
   case 2: str="TUESDAY";
           break;
   case 3: str="WEDNESDAY";
           break;
   case 4: str="THURSDAY";
           break;
   case 5: str="FRIDAY";
           break;
   case 6: str="SATURDAY";
           break;
   case 7: str="SUNDAY";
          break;
   }

    return str;
 }

I hope it does make sense to you....