cpointersc-stringsstrcatfunction-definition

C error expected ‘char **’ but argument is of type ‘char (*)[10]’


I am trying to implement my version of strcat. However, I get below warning and my code crashes while running. I am passing &p from main to make permanent changes to variable p in the main function.

Warning:

note: expected ‘char **’ but argument is of type ‘char (*)[10]’

Code:

#include <string.h>
#include <stdio.h>

void mystrcat(char **p, char *q)
{
    while (**p != '\0')
    {
        *p++;
    }

    while (*q != '\0')
    {
        **p = *q;
        (*p)++;
        q++;
    }
    *p = '\0';
}

int main()
{
    char p[10] = "ravi";
    char q[12] = "ra";

    mystrcat(&p, q);
    printf("%s", p);
}

Solution

  • Instead of a pointer to a pointer to char, just pass a pointer to char, it will also make the modification permanent. That's pretty much how the string.h strcat works. Maybe also check for NULL pointers.

    #include <stdio.h>
    #include <stdlib.h>
    
    char *mystrcat(char *p, char *q)
    {
        char *ptr = p; /* so you dont alter p's initial address */
    
        if (p == NULL || q == NULL)
        {
            exit(EXIT_FAILURE);
        }
    
        while(*ptr != '\0')
        {
            ptr++;
        }
    
        while(*q != '\0')
        {
            *ptr = *q;
            ptr++; /* you dont have to dereference */
            q++;
        }
        *ptr = '\0';
    
        return p;
    }
    
    int main(void)
    {
        char p[100]="hello";
        char q[12]="world";
    
        mystrcat(p, q);
        printf("%s", p);
    
        return 0;
    }