0

I want to print month name which is an array element (return from function as a pointer..)

This is my function:

/*I have taken this from book by Dennis Ritchie*/
/* month name : return name of n-th month */
char *month_name(int n){
     static char *name[] = {
     "illegal month","January","February","March","April","May","June","July",
     "August","September","October","November","December"};
return (n < 1 || n > 12) ? name[0] : name[n];
}

Now I am unable to collect this pointer in my main() function. I have tried this way

void main(void)
{
 int k = 0, i = 0;
 char *s;
 printf("Enter month number\n");
 scanf("%d",&k);

 s = month_name(k);
 for(i = 0; *(s+i) != '/0'; i++)
      printf("%c",*(s+i));
 getch();
}
6
  • You've got any issues with puts(month_name(k))? Commented Jul 31, 2015 at 7:46
  • 2
    Typo: '/0' should be '\0' Commented Jul 31, 2015 at 7:48
  • 2
    In your for loop: '/0' should be '\0' Commented Jul 31, 2015 at 7:50
  • 2
    I'm surprised your compiler didn't warn you about that. GCC says warning: multi-character character constant Commented Jul 31, 2015 at 7:51
  • sorry frnds.... I got the output.. @Barmar & Dmitri .... it was typing mistake.. Commented Jul 31, 2015 at 7:55

3 Answers 3

2

The reason why it is not working is because the following is incorrect

for ( i = 0; *(s+i) != '/0'; i++)

What you are trying to achieve in reality is to stop at null terminator. However! The null terminator in your code is incorrect.

Please change to the following:

for ( i = 0; *(s+i) != '\0'; i++)

Null terminator = '\0'. You wrote '/0'.

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

Comments

1

You can correct the null-typo, as others already suggested.

However, if you don't mind an alternate approach, as your function is returning a string, you can use the %s format specifier to print that directly, like

 printf("Month is %s\n", month_name(k));

Alternatively, as you're going to print a string directly, you can also write

  puts(month_name(k)));

Please note, void main(void) is not a valid signature for main(), as mandated by the standard. You should be using int main(void) instead.

Comments

0

You can simply use:

int main(void)
{
   int k = 0, i = 0;
   char *s;
   printf("Enter month number\n");
   scanf("%d",&k);

   printf("%s\n", month_name(k));

   return 0;
}

If you simply want to correct your code:

 for(i = 0; *(s+i) != '\0'; i++)
      printf("%c",*(s+i));

As you can see null termination is '\0' not '/0'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.