0

I cannot understand the last part of this function--strncat(t, s + i, 1). Since s is a char pointer and i is an integer, why can we add them together? What is the meaning of this line?

char* htmlspecialchars(const char* s)
{
    // ensure s is not NULL
    if (s == NULL)
    {
        return NULL;
    }

    // allocate enough space for an unescaped copy of s
    char* t = malloc(strlen(s) + 1);
    if (t == NULL)
    {
        return NULL;
    }
    t[0] = '\0';

    // iterate over characters in s, escaping as needed
    for (int i = 0, old = strlen(s), new = old; i < old; i++)
    {
        // escape &
        if (s[i] == '&')
        {
        //& is HTML for "Start of a character reference". &amp; is the character reference for "An ampersand".
            const char* entity = "&amp;";
            new += strlen(entity);
            t = realloc(t, new);
            if (t == NULL)
            {
                return NULL;
            }
            strcat(t, entity);
        }

        // escape "
        else if (s[i] == '"')
        {
            const char* entity = "&quot;";
            new += strlen(entity);
            t = realloc(t, new);
            if (t == NULL)
            {
                return NULL;
            }
            strcat(t, entity);
        }

        // escape '
        else if (s[i] == '\'')
        {
            const char* entity = "&#039;";
            new += strlen(entity);
            t = realloc(t, new);
            if (t == NULL)
            {
                return NULL;
            }
            strcat(t, entity);
        }

        // escape <
        else if (s[i] == '<')
        {
            const char* entity = "&lt;";
            new += strlen(entity);
            t = realloc(t, new);
            if (t == NULL)
            {
                return NULL;
            }
            strcat(t, entity);
        }

        // escape >
        else if (s[i] == '>')
        {
            const char* entity = "&gt;";
            new += strlen(entity);
            t = realloc(t, new);
            if (t == NULL)
            {
                return NULL;
            }
            strcat(t, entity);
        }

        // don't escape
        else
        {
            strncat(t, s + i, 1);
        }
    }

    // escaped string
    return t;
}
0

You can use addition of a pointer and an integer to gain a pointer to a specific array element.

s+i is the same as &s[i]

*(s+i) is the same as s[i]

Somebody compiled a PDF How To Write Unmaintainable Code, in the chapter C's Eccentric View Of Arrays you can find that s[i] is even the same as i[s]: s[i] is *(s+i) is *(i+s) is i[s].

1
  • It is very helpful. Thanks!
    – Charlotte
    Nov 29 '16 at 17:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .