输出月份英文名(20 分)

来源:互联网 发布:美橙互联和阿里云 编辑:程序博客网 时间:2024/05/21 10:27

本题要求实现函数,可以返回一个给定月份的英文名称。

函数接口定义:

char *getmonth( int n );
函数getmonth应返回存储了n对应的月份英文名称的字符串头指针。如果传入的参数n不是一个代表月份的数字,则返回空指针NULL。

裁判测试程序样例:

#include <stdio.h>char *getmonth( int n );int main(){    int n;    char *s;    scanf("%d", &n);    s = getmonth(n);    if ( s==NULL ) printf("wrong input!\n");    else printf("%s\n", s);    return 0;}/* 你的代码将被嵌在这里 */

输入样例1:

5

输出样例1:

May

输入样例2:

15

输出样例2:

wrong input!

起初的思路:

#include <stdio.h>char *getmonth( int n );int main(){    int n;    char *s;    scanf("%d", &n);    s = getmonth(n);    if ( s==NULL ) printf("wrong input!\n");    else printf("%s\n", s);    return 0;}char *getmonth( int n ){    char *month;    char mon[12][10]={"January","February","March","April","May","June","July","August","September","October","November","December" };    month=NULL;    if(n<=0||n>12)        return month;    month=mon[n-1];    //printf("month=%p\n",month);    return month;}

这个编译后输出不了正确结果,原因是定义的二维数组是在函数内部定义的,属于局部变量,只在函数内部起作用。在执行函数调用时,系统在栈上为函数内部的局部变量及形参分配内存,函数执行结束时,自动释放这些内存。所以,这时我们需要动态分配这些内存。
修改后的代码:

char *getmonth( int n ){    char *month;    char **mon;    int i;    mon=(char **)malloc(12*sizeof(char *));    mon[0]=(char *)malloc(12*10*sizeof(char));    for(i=1;i<12;i++)        mon[i]=mon[0]+i*10;    strcpy(mon[0],"January");    strcpy(mon[1],"February");    strcpy(mon[2],"March");    strcpy(mon[3],"April");    strcpy(mon[4],"May");    strcpy(mon[5],"June");    strcpy(mon[6],"July");    strcpy(mon[7],"August");    strcpy(mon[8],"September");    strcpy(mon[9],"October");    strcpy(mon[10],"November");    strcpy(mon[11],"December");    month=NULL;    if(n<=0||n>12)        return month;    month=mon[n-1];    return month;}

当然也可以改成这样

对数组进行malloc动态分配的一些总结


当然也可以不用动态分配,直接将二维数组设成全局变量

char mon[12][10]={"January","February","March","April","May","June","July","August","September","October","November","December" };char *getmonth( int n ){    char *month;    month=NULL;    if(n<=0||n>12)        return month;    month=mon[n-1];    return month;}

一个switch也能完成

char *getmonth( int n ){    switch(n)    {    case 1:return "January";    case 2:return "February";    case 3:return "March";    case 4:return "April";    case 5:return "May";    case 6:return "June";    case 7:return "July";    case 8:return "August";    case 9:return "September";    case 10:return "October";    case 11:return "November";    case 12:return "December";    default:return NULL;    }}
原创粉丝点击