modify existing char* or create a tmp char*?

Some languages, like Java, require you to create another string in order to solve certain kinds of problems. But when it comes to C, when should you create another string and when should you simply modify an existing one?

take the following code as an example:

    char *removeTags(char *s, int length)
{
    if (!s || length < 1)
    {
        exit(EXIT_FAILURE);
    }
    char *tmp = calloc(length, sizeof(char));
    int count = 0;
    for (int i = 0; i < length; i++)
    {
        if (s[i] == '<')
        {
            for (int k = i; k < length; k++)
            {
                if (s[k] == '>')
                {
                    i = k;
                    break;
                }
            }
        }
        else if (s[i] != '>' && s[i] != '<')
        {
            tmp[count] = s[i];
            count++;
        }
    }
    return tmp;
}

it should be called as following:

char *foo = (char *)calloc(length, sizeof(char)); foo = removeTags(foo, strlen(foo));

would it be better if i just modified the char *s instead of creating the char *tmp to help me?

>Solution :

If the function deals with strings then the second parameter is redundant and error-prone

char *removeTags(char *s, int length)

If you want to create a new string then the function must be declared like

char * removeTags( const char *s );

That is the function parameter shall have the qualifier const.

If you want to change a string in place then the function must be declared like

char * removeTags( char *s );

Pay attention to that you may not change string literals.

If you pass to the function also string literals then the function must be declared like

char * removeTags( const char *s );

You could define the both functions but in this case you need to use different function names.

Leave a Reply