Home > Back-end >  How exactly does pointer value incrementing work?
How exactly does pointer value incrementing work?

Time:11-01

so I was working on creating the raw function of concatenating a string in c. One solution that was provided to me was :

char *_strcat(char *dest, char *src)
{
    int c, c2;

    c = 0;

    while (dest[c])
        c  ;

    for (c2 = 0; src[c2] ; c2  )
        dest[c  ] = src[c2];

    return (dest);
}

The part that confuses me is while (dest[c]), and other similar parts. I've already gone through pointers through various resources but I can't seem to understand this part. A good explanation will be much appreciated.

CodePudding user response:

For starters the function is incorrect. It does not build a concatenated string because it does not append the terminating zero character '\0' to the result (dest) string in this for loop

for (c2 = 0; src[c2] ; c2  )
    dest[c  ] = src[c2];

Also the function should be declared like

char * _strcat( char *dest, const char *src );

because the appended string (src) is not changed.

This while loop

while (dest[c])
    c  ;

is equivalent to

while (dest[c] != '\0' )
    c  ;

and this for loop

for (c2 = 0; src[c2] ; c2  )
    dest[c  ] = src[c2];

is equivalent to

for (c2 = 0; src[c2] != '\0' ; c2  )
    dest[c  ] = src[c2];

That is the loops continue their iterations until the terminating zero character '\0' is encountered in the while loop in the string dest (to find its end) and in the second loop in the string src to find its end..

A non-zero scalar expression is evaluated as a logical true in conditions.

And the variables c and c2 should have the unsigned type size_t instead of the type int because objects of the type int can be not large enough to store string lengths.

Also you should not define names starting from the underscore character.

As for your question

How exactly does pointer value incrementing work?

then the pointers themselves are not incremented. There are used expressions with the subscript operator to access elements of strings as for example dest[c] or dest[c ] or src[c2].

The function can be defined the following way

char * my_strcat( char *dest, const char *src )
{
    char *p = dest;

    while ( *p != '\0' )   p;

    while ( ( *p   = *src   ) != '\0' );

    return dest;
}

In the shown function there are indeed incremented pointers p and src and neither expression with the subscript operator is used..

CodePudding user response:

char *dest is an pointer to char and it's pointed to the first character by default. Then the following loop will move the pointer offset to the end of the string.

c = 0;

while (dest[c])
   c  ;
  • Related