Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading