Results 1 to 9 of 9

Thread: [RESOLVED] Clarification required: char* and null terminators

Threaded View

  1. #1

    Thread Starter
    type Woss is new Grumpy; wossname's Avatar
    Join Date
    Aug 2002
    Location
    #!/bin/bash
    Posts
    5,682

    Resolved [RESOLVED] Clarification required: char* and null terminators

    I need a function to add an ordinal suffix to an integer. ie. ordinalize(...1) gives "1st", ordinalize(...2) gives "2nd" and so on.

    I'm porting some C# code that already does this but i'm uncertain about how to handle the null terminators on the end of the string...

    Code:
    void ordinalize(char *buf, int n);
    {
        char *ends[10] = {"th","st","nd","rd","th","th","th","th","th","th"};
        int t = (n < 0 ? -n : n) % 100;
        t %= ((t >= 11 && t <= 13) ? 1 : 10); //anything modded by 1 is always 0, this forcing a "th" out of the ends array...
    
        sprintf(buf, "%d%s", n, ends[t]);
    }
    (fills the buf array with the string we require)

    I'm calling this with:

    Code:
    char *temp[13]; //number will need 10 digits max plus 2 chars plus the null terminator
    ordinalize(temp, 12345);
    //temp now equals????
    My questions:
    1) Is a char array's contents always zeroes when its declared or is it undefined?
    2) Does sprintf add a null terminator?
    3) Do I need to manually add any null terminators anywhere?

    Last edited by wossname; Oct 9th, 2006 at 02:09 PM.
    I don't live here any more.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width