Right String – Solution

For this month’s Exercise, I offer both a string function solution as well as a solution that uses pointers. As you can guess, I thought of the string method first, which is where most programmers would run to avoid the dratted topic of pointers.

The same right() function declaration is used for both examples:

char *right(char *string, int size)

The text string is passed to the function. Variable size determines how many characters from the right side of string are returned, though technically a pointer to the start of that chunk is what’s returned.

For my non-pointer version, I crafted the following right() function:

char *right(char *string, int size)
{
    int len;

    len = strlen(string);
    return(string+len-size-1);
}

Variable len obtains the string’s length via the strlen() function. To get the position of the rightmost size characters, I use the calculation string+len-size-1. In this expression, string+len calculates the end of the string, where the null character ('\0') dwells. Subtract the value of size, plus 1 for the null character, to find the starting location of the rightmost size characters in string. That location (a pointer) is returned.

The pointer variation on the right() function doesn’t require the strlen() function. Instead, I loop through the string to find the null character:

char *right(char *string, int size)
{
    while(*string++)
        ;

    return(string-size-2);
}

The while loop processes the string for each non-null character. It stops when *string=='\0', but because of the ++ postfix, the pointer references the memory location after the '\0'.

In the return statement, the value of size is subtracted from string‘s memory location. Because string points at two characters beyond its end (the null character and whatever character follows it), the value 2 is subtracted.

WARNING: This variation is risky because string references a memory location beyond what’s allocated. A segmentation fault or similar error could generate at runtime should the memory location exist outside the program’s control.

Both functions yield the same output in my sample code:

http://c-for-dummies.com/images/c.png -> c.png
http://www.c-for-dummies.com/images/c.png -> c.png
/c-for-dummies.com/images/c.png -> c.png

Click here to view the first, string solution.

Click here to view the second, pointer solution.

If you came up with a different solution, wonderful! Ensure that you test your function to ensure that the rightmost n characters of the string are returned. I ran my functions through the paces, and they worked fine — just like that old BASIC language RIGHT$ function from long ago.

Leave a Reply