Thread: char*

  1. #1
    Registered User
    Join Date
    Oct 2001
    Posts
    4

    Question char*

    Hi there,

    I know pointers are messy, but can someone tell me what is wrong with this code. Do I need to use malloc, calloc, etc to initialize my char*?

    By the way, is there an easier way to return and array of char?

    code:
    char *cg_date (int t)
    {
    char *gtm;
    int day = t & 0x001F;
    int month = (t >> 5) & 0x000F;
    int year = ((t >> 9) & 0x007F) + 1980;

    switch (month)
    {
    case 1:
    strcpy (gtm, "Jan");
    break;
    case 2:
    strcpy (gtm, "Feb");
    break;
    case 3:
    strcpy (gtm, "Mar");
    break;
    case 4:
    strcpy (gtm, "Apr");
    break;
    case 5:
    strcpy (gtm, "May");
    break;
    case 6:
    strcpy (gtm, "Jun");
    break;
    case 7:
    strcpy (gtm, "Jul");
    break;
    case 8:
    strcpy (gtm, "Aug");
    break;
    case 9:
    strcpy (gtm, "Sep");
    break;
    case 10:
    strcpy (gtm, "Oct");
    break;
    case 11:
    strcpy (gtm, "Nov");
    break;
    case 12:
    strcpy (gtm, "Dec");
    break;
    default:
    strcpy (gtm, "Err");
    break;
    }
    return gtm;
    }

    Thanks

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > Do I need to use malloc, calloc, etc to initialize my char*?
    Yes - you're using gtm as the destination for a strcpy

    > By the way, is there an easier way to return and array of char?
    Yes.

    Given a function returning char*, you can write statements like
      return "Jan";

    To remove the case statement, I would put all the month names into an array
      char *month_names[] = { "Jan", "Feb", .... };
    and then simply do
      return month_names[month-1];
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    4
    Thanks.

    I changed the function to this instead:

    Code:
    char *cg_date (int t)
    {
    	static char gtm[255];
    						
    	char *mon_name[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
    	int day = t & 0x001F;
    	int month = (t >> 5) & 0x000F;
    	int year = ((t >> 9) & 0x007F) + 1980;
    
    	sprintf (gtm, "%s %d %d", mon_name[month-1], day, year);
    	return gtm;
    }

Popular pages Recent additions subscribe to a feed